不同群体的不同条件
different conditions on different groups
我有一个 table 这样的。我想获取按 ID 分组的第一行,其中 acc1 不为空,如果 acc1 中的所有行都为空,那么我想获取所有行。
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;
这假定 "first" 基于 acct1
、acct2
。 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
我有一个 table 这样的。我想获取按 ID 分组的第一行,其中 acc1 不为空,如果 acc1 中的所有行都为空,那么我想获取所有行。
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;
这假定 "first" 基于 acct1
、acct2
。 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