将行转换为列以删除 SQL 中公共值的重复条目
Convert rows to columns to remove duplicate entries on common value in SQL
我是 SQL 的初学者,正在尝试弄清楚如何将数据转换为列以删除重复条目。我试过 pivot,但我不需要聚合值。任何帮助将不胜感激。
当前状态:
ClientID
AddressType
Country
10001
Home
AU
10001
Postal
NZ
目标状态:
ClientID
Home
Postal
10001
AU
NZ
您可以使用 aggregation
或 case expression
轻松完成此操作
select clientId,
Max(case when AddressType='Home' then Country end) Home,
Max(case when AddressType='Postal' then Country end) Postal
from clients
group by ClientId
条件聚合是解决该问题的一种非常合理的方法。但是,如果您更喜欢其他方法,则可以使用 join
:
select th.clientid, th.country as home, tp.country as postal
from t th join
t tp
on th.clientid = tp.clientid and
th.addresstype = 'Home' and
tp.addresstype = 'Postal';
我是 SQL 的初学者,正在尝试弄清楚如何将数据转换为列以删除重复条目。我试过 pivot,但我不需要聚合值。任何帮助将不胜感激。
当前状态:
ClientID | AddressType | Country |
---|---|---|
10001 | Home | AU |
10001 | Postal | NZ |
目标状态:
ClientID | Home | Postal |
---|---|---|
10001 | AU | NZ |
您可以使用 aggregation
或 case expression
select clientId,
Max(case when AddressType='Home' then Country end) Home,
Max(case when AddressType='Postal' then Country end) Postal
from clients
group by ClientId
条件聚合是解决该问题的一种非常合理的方法。但是,如果您更喜欢其他方法,则可以使用 join
:
select th.clientid, th.country as home, tp.country as postal
from t th join
t tp
on th.clientid = tp.clientid and
th.addresstype = 'Home' and
tp.addresstype = 'Postal';