I have a table that I drew the following sample from:
Item <other columns> year month day
---- -- ------------ ---- ----- ---
VX4O GL 630.5938 2012 7 20
BX2T GL 0 2012 7 13
MWB806I GL 92004.72 2012 6 15
4XU GL 17.125 2012 7 20
VL4O GL 130.5 2012 7 20
MWB806I GL 92004 2012 10 26
MWB806I GL 92005 2012 11 30
3PU GL 25 2012 7 20
VC4O GL 630.6094 2012 7 20
MWB806I GL 92005 2012 11 2
The first column is Item, the last three columns are year, month, day.
How do I select the max date per item?
SELECT Item, MAX(CONVERT(DATETIME, RTRIM([year])
+ RIGHT('0'+RTRIM([month]), 2)
+ RIGHT('0'+RTRIM([day], 2)
)
FROM dbo.table
GROUP BY Item;
Now you really should consider fixing this schema. Why are you storing year/month/day separately? All it does is make calculations like this one much more difficult, and prevents any proper validation (you can have check constraints for basic stuff, but these are much more complex for things like leap years). And it doesn't save you any space (in fact you lose space if month/day are int, or if you can use smalldatetime).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.