SQL有条件地选择非空行

SQL有条件地选择非空行,sql,teradata,Sql,Teradata,我有一个关于teradata的如下表 每个客户在表中最多可以有2行-一行填充了地址,另一行地址为空。因此,一些客户只能有一行地址。有些只能有一行没有地址。有些可以有两行,一行有地址,一行没有地址 我想要一个每个客户一行的输出表——如果有地址,那么我想要那一行,如果没有,我想要空行。我尝试过使用case语句和where语句,但似乎无法让它们发挥作用。似乎我需要一个类似于文本的max函数 表1: cust_id address 1 abc 1 2 3

我有一个关于teradata的如下表

每个客户在表中最多可以有2行-一行填充了地址,另一行地址为空。因此,一些客户只能有一行地址。有些只能有一行没有地址。有些可以有两行,一行有地址,一行没有地址

我想要一个每个客户一行的输出表——如果有地址,那么我想要那一行,如果没有,我想要空行。我尝试过使用case语句和where语句,但似乎无法让它们发挥作用。似乎我需要一个类似于文本的max函数

表1

cust_id     address
1           abc
1   
2   
3           xyz
输出

cust_id      address
1            abc
2   
3            xyz

您可以将
groupby
子句与
max
聚合函数一起使用:

select cust_id, max(address)
from tbl
group by cust_id

您可以将
groupby
子句与
max
聚合函数一起使用:

select cust_id, max(address)
from tbl
group by cust_id

groupby
方法是最简单的表示方法。使用正确的索引,
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);

注意:这样做的优点/缺点是,对于给定的
客户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);

注意:这有一个优点/缺点,就是为给定的
客户id

保留所有非空值。谢谢,我刚刚更新了我的帖子,说我想我需要一个max函数来处理文本。我没有意识到我可以在文本中使用max。将尝试并确认。如果这些是真的空值,您甚至可以使用
min()
。谢谢,我刚刚更新了我的帖子,说我想我需要一个文本的max函数。我没有意识到我可以在文本中使用max。将尝试并确认。如果这些为真空,您甚至可以使用
min()