【问题标题】:two same rows but one column with distinct value, how to combine them and get rid of another line两行相同但一列具有不同的值,如何将它们组合并摆脱另一行
【发布时间】:2019-03-28 14:48:14
【问题描述】:

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

【问题讨论】:

  • 每个案例最多有两行,还是可以更多?看一下 PIVOT 查询。请用正确的数据库标记问题,以及您尝试过的内容。谢谢
  • 您使用的是哪个 dbms?

标签: sql


【解决方案1】:

以下查询将根据上述输入样本为您提供正确的所需 o/p,否则对于标准,您可以使用 PIVOT 关键字来创建新列

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

【讨论】:

    【解决方案2】:

    你可以使用聚合:

    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 ;
    

    【讨论】:

    • 我添加了新的截图,我正在使用 sql server
    • @Mike 。 . .我不确定你的意思是什么。这个答案似乎可以满足您的要求。
    • 非常感谢。
    • @Gordon 如果我还有一个值 Code 3 或 Id3 值会怎样?
    • 根据我的示例,它按预期工作。谢谢。
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2017-02-14
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多