繁体   English   中英

不同群体的不同条件

[英]different conditions on different groups

我有一张这样的桌子。 我想获得按ID分组的第一行,其中acc1不为null,并且如果acc1中的所有行均为null,那么我想获取所有行。

id  acc1    acc2
1   null    1
1   1   1
1   1   2
1   2   2
2   null    1
2   null    2
2   null    3
2   null    4

我想得到这样的输出:

id  acc1    acc2
1   1   1
2   null    1
2   null    2
2   null    3
2   null    4

假设acc1在不为null时是唯一的(对于每个id):

select t.*
from (select t.*,
             rank() over (partition by id
                          order by (case when acc1 is null then 2 else 1 end), acct1
                         ) as seqnum
      from t
     ) t
where seqnum = 1;

如果不是唯一的,那么这需要做更多的工作:

select t.*
from (select t.*,
             row_number() over (partition by id
                                order by acct1, acct2
                               ) as seqnum,
             count(acct1) over (partition by id) as cnt
      from t
     ) t
where seqnum = 1 or cnt = 0;

假定“第一”基于acct1acct2 SQL表本质上是无序的,因此您需要一列来指定顺序。

SELECT *
FROM mytable
QUALIFY Max(acc1) Over (PARTITION BY id) IS NULL -- only NULLs
  OR Row_Number() Over (PARTITION BY id          -- or the first non-null value
                        ORDER BY acc1 NULLS LAST) = 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM