sql - 后缀 : How to select the first row of each group?

标签 sql postgresql greatest-n-per-group

使用此查询:

WITH responsesNew AS
(
  SELECT DISTINCT responses."studentId", notation, responses."givenHeart", 
  SUM(notation + responses."givenHeart") OVER (partition BY responses."studentId" 
  ORDER BY responses."createdAt") AS total, responses."createdAt",  
  FROM responses
)
SELECT responsesNew."studentId", notation, responsesNew."givenHeart", total, 
responsesNew."createdAt"
FROM responsesNew
WHERE total = 3
GROUP BY responsesNew."studentId", notation, responsesNew."givenHeart", total, 
responsesNew."createdAt"
ORDER BY responsesNew."studentId" ASC

我得到这个数据表:

studentId | notation | givenHeart | total |      createdAt     |
----------+----------+------------+-------+--------------------+
 374      | 1        | 0          | 3     | 2017-02-13 12:43:03   
 374      | null     | 0          | 3     | 2017-02-15 22:22:17
 639      | 1        | 2          | 3     | 2017-04-03 17:21:30 
 790      | 1        | 0          | 3     | 2017-02-12 21:12:23
 ...

我的目标是只在我的数据表中保留每个组的前一行,如下所示:

studentId | notation | givenHeart | total |      createdAt     |
----------+----------+------------+-------+--------------------+
 374      | 1        | 0          | 3     | 2017-02-13 12:43:03 
 639      | 1        | 2          | 3     | 2017-04-03 17:21:30 
 790      | 1        | 0          | 3     | 2017-02-12 21:12:23
 ...

我怎样才能到达那里?

我在这里阅读了很多主题,但我没有尝试使用 DISTINCTDISTINCT ONWHERE 中的子查询、LIMIT 等对我有用(肯定是因为我的理解力差)。我遇到过与窗口函数相关的错误、ORDER BY 中缺少列以及其他一些我不记得的错误。

最佳答案

您可以使用 distinct on 来做到这一点。查询看起来像这样:

WITH responsesNew AS (
      SELECT DISTINCT r."studentId", notation, r."givenHeart", 
             SUM(notation + r."givenHeart") OVER (partition BY r."studentId" 
                                                  ORDER BY r."createdAt") AS total,
             r."createdAt" 
      FROM responses r
     )
SELECT DISTINCT ON (r."studentId") r."studentId", notation, r."givenHeart", total, 
r."createdAt"
FROM responsesNew r
WHERE total = 3
ORDER BY r."studentId" ASC, r."createdAt";

我很确定这可以简化。我只是不明白 CTE 的目的。以这种方式使用 SELECT DISTINCT 非常奇怪。

如果您想要一个简化的查询,请问另一个问题,其中包含样本数据、所需结果和对您正在做的事情的解释,并包括查询或指向该问题的链接。

关于sql - 后缀 : How to select the first row of each group?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43785841/

相关文章:

regex - Postgres 子字符串查找空间

sql选择排序结果的前n个唯一行

sql - 规范化非规范化表中的数据

PHP Laravel 错误 : Object of class stdClass could not be converted to string

java - spring boot通过schema.sql导入程序

sql - 使用 MAX() 和 GROUP BY 时如何选择整条记录

mysql - 如何使用Group By和self-join返回min, max, open, close daily price result set?

sql - 使用多个替换函数调用进行查询 - 如何提高性能?

sql - Rails - 如何避免对此进行多次查询

postgresql - 将数据库导出到 Heroku 时出现错误