使用以下查询:
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
中缺少列以及其他一些我记不清的错误。
Row_number() over (partition by studentID order by createdAt) RN
,然后在你的查询中添加where RN = 1。 - xQbert