Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Tototo1
Starting Member
22 Posts |
Posted - 2012-03-15 : 15:26:20
|
| I am having trouble coming up with an idea of how to take a large group of data, group by a certain parameter and only take the most recent data. I will explain below.I have a table with lmatter, linvoice and ldate. There are multiple lmatters and multiple linvoices that belong to seperate lmatters. lmatter linvoice ldate111 100 1992-05-06 00:00:00.000111 101 1992-06-06 00:00:00.000112 134 1992-04-15 00:00:00.000112 102 1992-01-01 00:00:00.000112 116 1992-07-19 00:00:00.000113 198 1992-03-03 00:00:00.000113 201 1993-01-01 00:00:00.000113 125 1992-06-17 00:00:00.000I would like to return the following:111 101 1992-06-06 00:00:00.000112 116 1992-07-19 00:00:00.000113 201 1993-01-01 00:00:00.000I have been poking around my little SQL book for ideas but I do not even know where to begin. I tried to use the TOP command but didn't have any luck. Any ideas that could help me on my way? Thanks! |
|
|
X002548
Not Just a Number
15586 Posts |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-03-15 : 15:31:24
|
use ROW_NUMBERSELECT required columns...FROM(SELECT ROW_NUMBER() OVER (PARTITION BY lmatter ORDER BY ldate DESC) AS Rn,*FROM table)tWHERE rn=1 ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-03-15 : 15:34:57
|
couple of other methods just FYIusing apply operatorSELECT t.*FROM table tCROSS APPLY (SELECT Max(ldate) AS latest FROM table WHERE lmatter = t.lmatter )t1WHERE latest = ldateusing derived table (sql 2000)SELECTFROM table tINNER JOIN (SELECT lmatter,MAX(ldate) AS latest FROM table GROUP BY lmatter )t1ON t1.lmatter = t.lmatterAND t1.latest = t.ldate ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|