返回sql组的第二条newst记录

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

我有一张如下的table:

coworker            date
   1             2020.10.30
   1             2019.09.12
   1             2018.05.29
   2             2019.08.07
   3             2020.03.12
   3             2018.06.24
   4             2020.08.16

我怎样才能得到这个:

coworker            date
   1             2019.09.12
   2             2019.08.07
   3             2018.06.24
   4             2020.08.16

如果同事不止一个,或者只有一个在场,那么结果应该是同事的第二个最新记录
谢谢你的帮助!

brgchamk

brgchamk1#

使用window函数尝试以下操作 row_number . 这是演示。

select
    coworker,
    date
from
(
    select
        *,
        row_number() over (partition by coworker order by date) as rn,
        count(*) over (partition by coworker) as ttl
    from myTable
) subq
where (ttl > 1 and rn = ttl - 1) or (ttl = 1 and rn = 1);

输出:

| coworker | date       |
| -------- | ---------- |
| 1        | 2019-09-12 |
| 2        | 2019-08-07 |
| 3        | 2018-06-24 |
| 4        | 2020-08-16 |
hfsqlsce

hfsqlsce2#

row_number() 功能可能有帮助:

select coworker, date 
from (
    select coworker, date, 
    count(*) over (partition by coworker) as count, 
    row_number() over (partition by coworker order by date desc) as order
    from MyTable
) t
where count = 1 OR (count > 1 and order = 2)

相关问题