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