两行相同,但一列具有不同的值,如何合并它们并摆脱另一行

时间:2019-03-28 14:48:15

标签: sql

enter image description here我有两行值完全相同,除了一列外,我想将它们合并并将另一值添加到新列中

Name       Address        City    State    ID        ID Type
XYZ        123 address     New York  NY     123      Code1
XYZ       123 address      New York   NY    D561      Code2
ABC        895 address     Richmond    VA    568A      Code1
XAB        456 address     Dallas      TX    568       Code2
XAB        456 address      Dallas     TX    458A562    Code1
XYZ       123 address         New York  NY   123T        Code3

结果

Name       Address      City   State    Code1   Code2  code3
XYZ        123 Address   New York  NY   123      D561  123T
ABC        895 address    Richmond  VA  568A
XAB        456 address    Dallas    TX  458A562   563

enter image description here

2 个答案:

答案 0 :(得分:1)

以下查询将根据上述输入示例为您提供正确的所需操作数,或者对于标准,您可以使用PIVOT关键字添加新列

SELECT  Name, Address,City, State,   
        min(ID) AS ID1,max(ID) AS ID2 
FROM your_table
GROUP BY Name, Address,City, State

答案 1 :(得分:0)

您可以使用聚合:

select Name, Addresss, City, State,
       min(id) as id1,
       (case when min(id) <> max(id) then max(id) end) as id2 
from t
group by Name, Addresss, City, State ;