October 24, 2008 at 5:34 pm
Sample data:
create table #a
(ID int identity (1,1)
, AgentID varchar(10)
, TransDate datetime
, AgentType varchar (10))
insert #a (AgentID, TransDate, AgentType)
select 'AAA', '5/7/08', 'Standard'
union
select 'AAA', '5/8/08', 'Standard'
union
select 'BBB', '5/8/08', 'Standard'
union
select 'BBB', '5/9/08', 'Advanced'
union
select 'CCC', '5/9/08', 'Standard'
union
select 'AAA', '6/1/08', 'Advanced'
union
select 'AAA', '7/7/08', 'Standard'
union
select 'CCC', '8/7/08', 'Standard'
I need to get the latest AgentType for each agent. Expected result:
AgentIDAgentType
AAAStandard
BBBAdvanced
CCCStandard
My query below works but I am sure it doesn't look professional:
select AgentID, AgentType from #a where AgentID + cast(TransDate as varchar (30)) in
(select distinct AgentID + cast(max(TransDate) as varchar (30)) from #a group by AgentID)
Is there another query producing exprected result?
Regards,
October 24, 2008 at 6:35 pm
You can use a common table expression to store the agentid with the max date and then join it back to the original table to limit the results.
create table #a
(ID int identity (1,1)
, AgentID varchar(10)
, TransDate datetime
, AgentType varchar (10))
insert #a (AgentID, TransDate, AgentType)
select 'AAA', '5/7/08', 'Standard'
union
select 'AAA', '5/8/08', 'Standard'
union
select 'BBB', '5/8/08', 'Standard'
union
select 'BBB', '5/9/08', 'Advanced'
union
select 'CCC', '5/9/08', 'Standard'
union
select 'AAA', '6/1/08', 'Advanced'
union
select 'AAA', '7/7/08', 'Standard'
union
select 'CCC', '8/7/08', 'Standard'
;
With cteMaxTranDate
AS
(
select AgentID, max(TransDate) MaxTransDate
from #a group by AgentID
)
select #a.AgentID, #a.AgentType
from #a Join
cteMaxTranDate ON
#a.AgentID = cteMaxTranDate.AgentID AND
#a.TransDate = cteMaxTranDate.MaxTransDate
Drop Table #a
October 25, 2008 at 8:43 am
Doing it the old fashioned way using a "Derived table" instead of a CTE...
SELECT orig.AgentID, orig.AgentType
FROM #a orig
INNER JOIN
(SELECT AgentID, MAX(TransDate) AS MaxTransDate FROM #a GROUP BY AgentID) maxdate
ON Orig.AgentID = maxdate.AgentID
AND orig.TransDate = maxdate.MaxTransDate
ORDER BY orig.AgentID
Note that you do not need any date conversions for this or the CTE version that Ken wrote. They just slow things down.
--Jeff Moden
Change is inevitable... Change for the better is not.
October 27, 2008 at 9:56 am
Thanks!
I also found this qurey worked for me:
select a.AgentID, a.AgentType from
(select AgentID, row_number() over (partition by AgentID order by TransDate desc) as row, TransDate, AgentType from #a) a
where a.row = 1
I am kind of behind so there are new things in SQL 2005 I haven't learned and used :blink:
October 27, 2008 at 6:45 pm
You don't need to include TransDate in that... just wasted IO and clock cycles. 🙂
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply