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 |
|
smh
Yak Posting Veteran
94 Posts |
Posted - 2010-06-19 : 00:05:28
|
| Not sure if this is a group by or a partition query.I have a table:id pos effectivedate1 23 1/1/20102 23 3/3/20103 24 1/1/20104 25 4/7/20105 25 5/5/20106 25 7/7/2010I have to create a query where the EffectiveDate <= 6/6/2010 grouped by position and using the position with the most recent date.So the results would beid pos effectivedate2 23 3/3/20103 24 1/1/20105 25 5/5/2010I can get a result not filtering the effective date and not including the ID, i.e. that would be grouping the pos by the most recent effective date, but I can't seem to figure out how to only select the dates <= 5/5/2010 and also to keep the id in the query since I need it for later joins. I tried using having max(effectivedate) <= ... but that did not group the pos correctly.Would appreciate some help on this.Thanks so much. |
|
|
grasshopper
Starting Member
1 Post |
Posted - 2010-06-19 : 06:10:58
|
| You can use a common table expression (available in SQL 2005 and SQL 2008) as follows:------------------------------------------------------WITH MaxTable ( pos, effectivedate)AS( select pos, max(effectivedate) AS MAXDatefrom t1 WHERE effectivedate <= CONVERT(VARCHAR,'6/6/2010',1)group by pos)SELECT t.ID, t.POS, CONVERT(VARCHAR,t.EFFECTIVEDATE,101) AS EFFECTIVEDATEFROM t1 t INNER JOIN MaxTable m ON t.POS = m.POSAND t.effectivedate = m.effectivedateORDER BY t.ID------------------------------------------------------The result will be:ID POS EFFECTIVEDATE----------- ----------- ------------------------------2 23 03/03/20103 24 01/01/20105 25 05/05/2010(3 row(s) affected) |
 |
|
|
smh
Yak Posting Veteran
94 Posts |
Posted - 2010-06-19 : 12:18:10
|
| Thank you. This works like a charm. I have never seen the Common Table Expression. This is quite useful. |
 |
|
|
|
|
|