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 |
cornall
Posting Yak Master
148 Posts |
Posted - 2009-04-17 : 11:07:38
|
Hi,If I have a table type, date, value1 2009-01-01 101 2009-01-03 112 2009-01-01 142 2009-01-03 10and I join to this table based on type how do I select the value for the max(date)SELECT b.valueFROM a LEFT JOIN b ON a.type = b.typeWhat do I need to get the value for max date?Hope this makes sense. |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-04-17 : 11:23:34
|
if dates wont repeat thenSELECT TOP 1 b.valueFROM a LEFT JOIN b ON a.type = b.typeORDER BY b.date DESCand if it repeatsSELECT b.valueFROM a LEFT JOIN b ON a.type = b.typeWHERE b.date = (SELECT MAX(date) FROM b) |
|
|
cornall
Posting Yak Master
148 Posts |
Posted - 2009-04-17 : 11:26:00
|
Sorry I need it for each typeso it should return11 and 14 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-04-17 : 11:32:25
|
[code]SELECT a.*FROM table a INNER JOIN (SELECT type,MAX(date) AS latest FROM table GROUP BY type)b ON a.type = b.typeAND a.date=b.latest[/code] |
|
|
cornall
Posting Yak Master
148 Posts |
Posted - 2009-04-17 : 11:47:34
|
Thanks again but table a doesn't have date for a.date=b.latest |
|
|
cornall
Posting Yak Master
148 Posts |
Posted - 2009-04-17 : 11:49:16
|
forget the join how do I gettype, date, value1 2009-01-01 101 2009-01-03 112 2009-01-01 142 2009-01-03 10value for each type with max date from the above. |
|
|
cornall
Posting Yak Master
148 Posts |
Posted - 2009-04-17 : 11:59:04
|
Is it just SELECT type,value FROM table WHERE date IN (SELECT MAX(date) FROM table GROUP BY type) |
|
|
cornall
Posting Yak Master
148 Posts |
Posted - 2009-04-17 : 12:07:57
|
Sorry ignore my nonsense I see you are joining the table to itself referenced as a then b!!Thanks for all your help. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-04-17 : 13:47:08
|
welcome |
|
|
|
|
|