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
...
我该如何到达那里?
我读过许多问题在这里,但没有我曾与尝试DISTINCT
,DISTINCT ON
,在WHERE
,LIMIT
,等我工作过(当然,由于我缺乏了解)子查询。我遇到了与窗口函数有关的错误,缺少ORDER BY
中的列和其他一些我不记得的列。
使用窗函数在with语句被它'ROW_NUMBER()以上(分区由studentID为了通过createdAt)添加ROW_NUMBER和过滤RN'然后添加其中RN = 1到您的查询。 – xQbert