greatest-n-per-group查询,包括没有“n”的行

nkoocmlb  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(275)

我知道这是一个常见的问题,但我还没有找到这个具体问题的答案:
我有两张table:

+--------------+     +-------------------------------+
| temp1        |     | temp2                         |
+----+---------+     +----+----+---------------------+
| id | name    |     | id | fk | ts                  |
+----+---------+     +----+--------------------------+
| 1  | first   |     | 1  | 1  | 2020-06-19 23:56:46 | 
| 2  | second  |     | 2  | 1  | 2020-06-19 22:56:46 | 
| 3  | third   |     | 3  | 2  | 2020-06-19 21:56:46 | 
+----+---------+     | 4  | 2  | 2020-06-19 20:56:46 | 
                     +----+--------------------------+

为了为temp1中的每个条目获取temp2中具有最新时间戳的对应条目,我正在运行以下查询:

SELECT 
    t1.id AS id,
    t1.name AS name,
    t2.ts AS ts
FROM
    (temp2 t2
    JOIN temp1 t1)
WHERE
    t2.ts = (SELECT MAX(t3.ts)
        FROM
            temp2 t3
        WHERE
            t2.fk = t3.fk)
        AND t2.fk = t1.id

这将导致:

+----+--------+---------------------+
| id | name   | ts                  |
+----+------------------------------+
| 1  | first  | 2020-06-19 23:56:46 | 
| 2  | second | 2020-06-19 21:56:46 | 
+----+------------------------------+

是否可以更改此查询以包含temp1中没有对应temp2值的行?
预期结果是:

+----+--------+---------------------+
| id | name   | ts                  |
+----+------------------------------+
| 1  | first  | 2020-06-19 23:56:46 | 
| 2  | second | 2020-06-19 21:56:46 | 
| 3  | third  | NULL                | 
+----+------------------------------+
pxyaymoc

pxyaymoc1#

使用窗口功能:

SELECT t1.id, t1.name, t2.ts
FROM t1 LEFT JOIN
     (SELECT t2.*, ROW_NUMBER() OVER (PARTITION BY t2.fk ORDER BY t2.ts DESC) as seqnum
      FROM temp2 t2
     ) t2
     ON t2.fk = t1.id AND seqnum = 1;
k7fdbhmy

k7fdbhmy2#

最简单的方法是在 SELECT 列表:

SELECT t1.*,
  (SELECT MAX(t2.ts) FROM temp2 t2 WHERE t2.fk = t1.id) ts
FROM temp1 t1

请看演示。
结果:

| id  | name   | ts                  |
| --- | ------ | ------------------- |
| 1   | first  | 2020-06-19 23:56:46 |
| 2   | second | 2020-06-19 21:56:46 |
| 3   | third  |                     |

相关问题