SQL 有条件地选择非空行
SQL Selecting non-null rows conditionally
我在 teradata 上有一个 table,如下所示。
每个客户在 table 中最多可以有 2 行 - 一行填充了地址,另一行地址为空。所以有些客户只能有一行地址。有些可以只有一行没有地址。有些可以有 2 行,一排有地址,一排没有地址。
我想要输出 table 每个客户一行 - 如果有地址,那么我想要该行,如果没有,我想要空行。我试过使用 case 语句和 where 语句,但我似乎无法让它们工作。好像我需要像 max 文本函数这样的东西。
Table 1:
cust_id address
1 abc
1
2
3 xyz
输出:
cust_id address
1 abc
2
3 xyz
您可以将 group by
子句与 max
聚合函数一起使用:
select cust_id, max(address)
from tbl
group by cust_id
group by
方法是最简单的表达方法。使用正确的索引,union all
可能会有更好的性能:
select *
from tbl
where address is not null
union all
select *
from tbl t2
where address is null and
not exists (select 1 from tbl t2 where t.cust_id = t2.cust_id and t2.address is not null);
注意:这具有 advantage/disadvantage 保留给定 cust_id
的所有非 NULL 值。
我在 teradata 上有一个 table,如下所示。
每个客户在 table 中最多可以有 2 行 - 一行填充了地址,另一行地址为空。所以有些客户只能有一行地址。有些可以只有一行没有地址。有些可以有 2 行,一排有地址,一排没有地址。
我想要输出 table 每个客户一行 - 如果有地址,那么我想要该行,如果没有,我想要空行。我试过使用 case 语句和 where 语句,但我似乎无法让它们工作。好像我需要像 max 文本函数这样的东西。
Table 1:
cust_id address
1 abc
1
2
3 xyz
输出:
cust_id address
1 abc
2
3 xyz
您可以将 group by
子句与 max
聚合函数一起使用:
select cust_id, max(address)
from tbl
group by cust_id
group by
方法是最简单的表达方法。使用正确的索引,union all
可能会有更好的性能:
select *
from tbl
where address is not null
union all
select *
from tbl t2
where address is null and
not exists (select 1 from tbl t2 where t.cust_id = t2.cust_id and t2.address is not null);
注意:这具有 advantage/disadvantage 保留给定 cust_id
的所有非 NULL 值。