不同群体的不同条件

时间:2017-07-10 16:29:37

标签: sql teradata

我有一张这样的桌子。我想得到第一行按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

2 个答案:

答案 0 :(得分:2)

假设acc1null(对于每个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表本质上是无序的,因此您需要一个指定排序的列。

答案 1 :(得分:2)

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
相关问题