I am working on a small reporting application. I have two tables
Agent Table Data
AgentID AgentName
------- ---------
1001 ABC
1002 XYZ
1003 POI
1004 JKL
Report Table Data
ReportID AgentId Labor Mandays Amount SubmitDate
-------- ------- ----- ------- ------ ----------
1 1001 30 10 5000 11/12/2011
2 1001 44 18 8000 11/14/2011
3 1002 33 75 3022 11/12/2011
4 1001 10 10 1500 11/14/2011
5 1002 10 10 1800 11/14/2011
6 1001 10 10 1400 11/14/2011
7 1003 40 40 1500 11/14/2011
8 1003 40 40 1800 11/14/2011
I want to generate a report which gives us output like
ReportID AgentId Labor Mandays Amount SubmitDate
-------- ------- ----- ------- ------ ----------
1 1001 30 10 5000 11/12/2011
3 1002 33 75 3022 11/12/2011
6 1001 10 10 1400 11/14/2011
5 1002 10 10 1800 11/14/2011
8 1003 40 40 1800 11/14/2011
Thanks in Advance
You didn’t mention what VERSION of SQL Server you’re using – if you’re on 2005 or newer, you can use a CTE (Common Table Expression) with the
ROW_NUMBERfunction:This CTE “partitions” your data by
AgentIDandSubmitDate, and for each partition, theROW_NUMBERfunction hands out sequential numbers, starting at 1 and ordered byReportID DESC– so the “last” row (with the highestReportID) for each(AgentID, SubmitDate)pair getsRowNum = 1which is what I select from the CTE in the SELECT statement after it.PS: this doesn’t work 100% on your input data, since you’ve not defined how to group and how to eliminate rows…. you might need to adapt this query a bit, based on your requirements…