请帮我解决一个我在工作中遇到的问题。我正在使用 SQL Server,我知道使用游标可以实现这一点,但我很确定有一种方法可以使用 SQL 中的简单查询来实现,但我的大脑灯泡不想这样做打开。让我用一个例子来解释我的问题。
我有一张这样的 table :
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 |
我想要完成的是获取所有帖子,但每个用户只有一个帖子(postedby 列),日期必须是最新的,当然还要显示评论。
我试过:
Select distinct postedby, date, comment
但没有用,因为我知道每列都有不同的作品,所以如果 postedby 的两行相同但评论不同,它会将其视为不同的
我试过:
选择 postedby,date,comment group by postedby
(不要理会 from 子句)
给我错误或聚合,所以我尝试了
select postedby,min(date) group by postedby
- 当然可以,但我无法获得评论。
我应该以某种方式使用聚合查询吗?或者我错过了什么?
最佳答案
看来今天是 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
关于sql - 选择整个表格但特定列中的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8793006/