SQL 服务器在分区内查找结果
SQL Server find results within partition
我有以下 table:
ID Date
-------------------
1 Null
1 1/2/2020
2 Null
2 12/2/2020
3 Null
对于每个至少有一个非空日期的ID,我需要分类为'accounted'。
结果集应如下所示:
id Date AccountFlag
----------------------------
1 Null Accounted
1 1/2/2020 Accounted
2 Null Accounted
2 12/2/2020 Accounted
3 Null Unaccounted
您可以使用 window 函数来检查相同的 id
是否至少有一个非 null
date
和一个 case
表达式来相应地设置标志。 Window 聚合函数派上用场:
select id, date,
case when max(date) over(partition by id) is not null
then 'Accounted'
ese 'Unaccounted'
end as accountflag
from mytable
max()
忽略 null
值,因此它 returns null
当且仅当分区中的所有值都是 null
时。这与 min()
.
一样有效
我有以下 table:
ID Date
-------------------
1 Null
1 1/2/2020
2 Null
2 12/2/2020
3 Null
对于每个至少有一个非空日期的ID,我需要分类为'accounted'。
结果集应如下所示:
id Date AccountFlag
----------------------------
1 Null Accounted
1 1/2/2020 Accounted
2 Null Accounted
2 12/2/2020 Accounted
3 Null Unaccounted
您可以使用 window 函数来检查相同的 id
是否至少有一个非 null
date
和一个 case
表达式来相应地设置标志。 Window 聚合函数派上用场:
select id, date,
case when max(date) over(partition by id) is not null
then 'Accounted'
ese 'Unaccounted'
end as accountflag
from mytable
max()
忽略 null
值,因此它 returns null
当且仅当分区中的所有值都是 null
时。这与 min()
.