What SQL query returns the row with the most recent Date and Time (Column B and C) for each unique Column A?

核能气质少年 提交于 2019-12-12 21:22:17

问题


What SQL query returns the row with the most recent Date and Time (Column B and C) for each unique Column A?


回答1:


If C is actually a datetime column with date and time information set, you can do:

select a, max(c)
  from table
 group by a;

If B is a date column and C is a time column, then you need:

select a, max(convert(varchar(15), b) + ' ' + convert(varchar(15), c))
  from table
 group by a;



回答2:


When I do:

select convert(varchar, getdate())

I get "Nov 19 2010 5:17PM", which doesn't help when finding the max().
I would spell out the style even if your database default doesn't have this problem. Something like:

select x.a,
cast(max(convert(varchar, x.b, 112)+' '+
convert(varchar, x.c, 108) as Datetime)) 
as maxDateTime
from table x
group by x.a

This produces "2010-11-19 17:20:29.000"

I know you are using Date type and Time type, but same idea.



来源:https://stackoverflow.com/questions/4227841/what-sql-query-returns-the-row-with-the-most-recent-date-and-time-column-b-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!