选择整个表,但在特定列中选择唯一值

Bla*_*Co. 3 sql group-by sql-server-2005 distinct aggregation

请帮助我解决我在工作中遇到的问题.我正在使用SQL Server,我知道使用游标我可以实现这一点,但我很确定在SQL中使用简单查询有一种方法,但我的大脑灯泡不想打开.让我用一个例子来解释我的问题.

我有一张这样的桌子:

postedby    |   date        |   comment |
1           |   01.01.2012  |   sth sth |
2           |   01.01.2012  |   sth sth |
3           |   01.01.2012  |   sth sth |
2           |   01.01.2012  |   sth sth |
3           |   02.01.2012  |   sth sth |
2           |   03.01.2012  |   sth sth |
2           |   05.01.2012  |   sth sth |
Run Code Online (Sandbox Code Playgroud)

我想要完成的是获取所有帖子,但每个用户一个(发布列),日期必须是最新的,当然显示评论.

我试过做:

Select distinct postedby, date, comment
Run Code Online (Sandbox Code Playgroud)

但是没有用,因为我理解每个列的不同作品,所以如果在postfrom中的两行是相同的但是注释是不同的,它会将它视为区别

我试过做:

Select postedby,date,comment group by postedby(不要理解from子句)给我错误或聚合,所以我尝试 select postedby,min(date) group by postedby- 当然有效,但我无法得到评论.

我应该以某种方式使用聚合查询吗?或者我错过了什么?

Bas*_*nni 7

看起来今天是RowNumber功能日!! 如果您需要的是每个帖子的最新日期和评论:

SELECT postedBy, date, comment
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY postedby, ORDER BY date DESC) AS RowNumber, 
             postedBy, date, comment
      FROM MyTable) t 
WHERE RowNumber = 1
Run Code Online (Sandbox Code Playgroud)