Share via

Filtering inside the PIVOT command

DotNetGuy-3168 1 Reputation point
2022-06-30T19:56:11.093+00:00

I'm trying to filter before I PIVOT. I only want the Fuel Surcharge from the ManifestRate table when the enddate is 12-31-9999. Problem is, the rest of the columns are in that table have enddates as well. Should I use a CASE statement or something? This is what I have so far:

SELECT * into #test1 FROM
(
select distinct m1.State, m1.Market, l.LabName, m.MnifestName, mr.ManifestId, r.RateName, mr.Value
from Manifests m
left join ManifestRate mr on m.ID = mr.ManifestId
inner join Markets m1 on m.Marketid = m1.ID
inner join labs l on l.labid = m.LabId
left join RateType r on mr.RateTypeId = r.RateTypeId
where m.IsActive = 1
and mr.Enddate = '12-31-9999'
) tp
PIVOT
(
max(Value)
FOR [RateName] in ([Fuel Surcharge %],[Supply Cost],[Linehaul Billing],[Linehaul Cost],[Dry Ice Billing],[Dry Ice Cost],[Supply Charge],[COB])
) p

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

2 answers

Sort by: Most helpful
  1. DotNetGuy-3168 1 Reputation point
    2022-07-01T14:01:31.81+00:00

    Thanks for your response. I will try this today ...

    Was this answer helpful?


  2. Naomi Nosonovsky 8,906 Reputation points
    2022-07-01T12:12:02.42+00:00

    You would need to use CASE or OR condition, e.g.
    SELECT * into #test1 FROM
    (
    select distinct m1.State, m1.Market, l.LabName, m.MnifestName, mr.ManifestId, r.RateName, mr.Value
    from Manifests m
    left join ManifestRate mr on m.ID = mr.ManifestId
    inner join Markets m1 on m.Marketid = m1.ID
    inner join labs l on l.labid = m.LabId
    left join RateType r on mr.RateTypeId = r.RateTypeId
    where m.IsActive = 1
    and ((mr.Enddate = '12-31-9999' and r.RateName = 'Fuel Surcharge %' )
    OR r.RateName <> 'Fuel Surcharge %' )
    ) tp
    PIVOT
    (
    max(Value)
    FOR [RateName] in ([Fuel Surcharge %],[Supply Cost],[Linehaul Billing],[Linehaul Cost],[Dry Ice Billing],[Dry Ice Cost],[Supply Charge],[COB])
    ) p

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.