utlonghornjulie
asked on
Trying to pull distinct IDs
I am trying to pull a list of distinct IDs based on maximum ContEnd_Switch date. If I change the ContEnd_Switch in the select statement to a MAX(ContEnd_Switch) and then take out the ContEnd_Switch in the Group by clause, then it won't work because I need a group by because I have ContEnd_Switch in the Order by clause. If I add Max(ContEnd_Switch) to the Having clause, for example Having Max(ContEnd_Switch) = ContEnd_Switch, then this will not work either because there are rows in the data with null ContEnd_Switch dates. Please help!
SELECT ProspectID, Prospect, ContEnd_Switch, TargetPrice, SUM(MwhAct * Total) / SUM(MwhAct) AS WAverage,
GM_MarRate, Comm_1_Rate, Comm_2_Rate, Comm_3_Rate, Comm_4_Rate, Comm_5_Rate, Comm_6_Rate
FROM Prospect_Cogs
WHERE (Fwd_Mth BETWEEN 1 AND 12) and SRID = 176 and (Realtime in (select Realtime from tbl_realtime) )
GROUP BY ProspectID, Prospect, TargetPrice, ContEnd_Switch, GM_MarRate, Comm_1_Rate, Comm_2_Rate, Comm_3_Rate, Comm_4_Rate, Comm_5_Rate, Comm_6_Rate
having SUM(MwhAct * Total) / SUM(MwhAct) > 0
order by CASE 0
when 1 then cast(ContEnd_Switch as varchar) -- by end contract
when 2 then cast(TargetPrice as varchar) -- Target Price
when 3 then cast(SUM(MwhAct * Total) / SUM(MwhAct) as varchar) --by quoted Price
else Prospect --by Prospect Name
END
i don't understand your query but i think the row_number() function can help you here
ASKER
I am trying to pull a list of distinct ProspectIDs. For the duplicate ProspectIDs, then I want the record that has the maximum ContEnd_Switch date.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.