我在 Postgres 中有一张表,其中包含如下数据:
fk | priority | date
1 1 4-1-2023
1 1 4-3-2023
1 2 4-5-2023
2 3 4-1-2023
2 2 4-2-2023
3 3 4-6-2023
我需要这样的结果:
fk | priority | date
1 1 4-3-2023
2 2 4-2-2023
3 3 4-6-2023
所以在 fk 的每个分组中,我想要最高优先级。 1为最高。如果有优先关系,那么我想要最近的日期。
我的 SQL 不是那么先进,我很难找到解决方案。提前致谢。
这可以通过带有子查询的窗口函数来完成(适用于多个 RDBMS)
SELECT fk, priority, mydate
FROM (
SELECT *, /* Return all the columns we want in the final query */
ROW_NUMBER() OVER (PARTITION BY fk ORDER BY priority, mydate DESC) AS rn
/*
Generate a row number,
restarting the numbering for each `fk` value seen (partition by)
Order the rows, first: the smallest number `priority` (ascending),
then: the latest `mydate` (descending)
Put the result in a column named `rn` to use in the outer query
*/
FROM mytable
) x
WHERE rn = 1 /* Filter by the `rn` value, return only the first row */
;
或者使用
DISTINCT ON
子句(更具体的 postgresql)
SELECT DISTINCT ON (fk) * /* Return a distinct row for each fk value */
FROM mytable
ORDER BY fk, priority, mydate DESC
/*
Order by which is the first row to return
It is required to include `fk` first because of the DISTINCT ON (fk),
but then: get the smallest `priority` (ascending),
then: the latest `mydate` (descending).
*/
;