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 |
gmartinezlozada
Starting Member
3 Posts |
Posted - 2014-03-04 : 14:40:06
|
I have a table and I need three columns:AdEnrollID (Foreign Key), SyStatchangeID (Primary KEY) and EffectiveDate (DateTime). I need the MAX(EffectiveDate) group by AdEnrollID but I also need the systatchangeID for that row.here is my query:Select AdEnrollID,SyStatChangeid, MAX(EffectiveDate)from systatchange where EffectiveDate < '8/1/2013' and adenrollID=47964Group by grouping sets ((SyStatChangeID, systatchange.AdEnrollID))but it gives me a lot of results (I know, I group by systatchangeID and is going to include them all) Here is the result:AdEnr SyStat (No column name)47964 274956 2012-08-07 12:44:36.78747964 277286 2012-09-05 09:32:02.48047964 278621 2012-09-13 13:45:11.84047964 279106 2012-09-19 14:58:33.08047964 285823 2012-12-07 15:14:01.08747964 288130 2011-06-09 00:00:00.00047964 291992 2011-06-09 00:00:00.00047964 307190 2011-06-09 00:00:00.00047964 246461 2011-06-09 14:46:22.82347964 246462 2011-06-09 14:46:23.12047964 263517 2012-01-25 13:31:11.49047964 273669 2012-07-23 12:17:41.03347964 311992 2011-06-09 00:00:00.000 I am only interested in the one in bold. How can I do this. |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2014-03-04 : 17:16:16
|
You can use th erow number function like this:SELECT AdEnrollID , SyStatChangeid , EffectiveDateFROM ( SELECT AdEnrollID , SyStatChangeid , EffectiveDate, ROW_NUMBER() OVER (PARTITION BY AdEnrrolID ORDER BY EffectiveDate DESC ) AS RN FROM systatchange WHERE EffectiveDate < '8/1/2013' AND adenrollID = 47964) sWHERE RN = 1; Also take a look at this thread for couple of alternatives, with explanations. http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=192905 |
|
|
gmartinezlozada
Starting Member
3 Posts |
Posted - 2014-03-05 : 12:52:13
|
Thank you so much. i will try this and let you know. |
|
|
gmartinezlozada
Starting Member
3 Posts |
Posted - 2014-03-07 : 09:19:12
|
Works like a charm. thanks a lot. |
|
|
|
|
|