sql - 选择整个表格但特定列中的唯一值

标签 sql sql-server-2005 group-by distinct aggregation

请帮我解决一个我在工作中遇到的问题。我正在使用 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/

相关文章:

SQL : Find the position of a character in a string value

mysql - 对两个表中的值进行一些计算并将其存储在其中一个表中

sql-server-2005 - 我应该如何在 SQL Server 2005 中实现 "autonumber"字段?

Mysql 数据库设计 - 捕获视频使用指标

sql - 添加列描述

sql - 使用 exec() 在 sp 内执行运行时查询时遇到错误 "The default schema does not exist."

python - GroupBy pandas DataFrame 并选择最常见的值

c# - 分组为元素字典

mysql - 如何使用 group by 子句从单个表中检索数据

sql 查询性能 - 行数较少的宽表或行数较多的窄表?