列需要根据值进行分隔并在其上分组

时间:2019-03-29 20:42:19

标签: sql sql-server

Name     Address    City        State    Id        IdType
---------------------------------------------------------
XYZ      123 Rd     New York    NY       123D      Code1
XYZ      123 Rd     New York    NY       56A45     Code2
XYZ      123 Rd     New York    NY       D45256    Code3
XYZ      123 Rd     New York    NY       345TT     Code2
ZZZ      456 St     Richmond    VA       1564      Code2
ABC      879 Rd     Tampa       FL       5687AB    Code1
ABC      879 Rd     Tampa       FL       546YYY    Code3

结果:

Name    Address    City        State    code1     code2    code2_II    Code3
XYZ     123 Rd     New York    NY       123D      56A45    345TT       D45256
ZZZ     456 St     Richmond    VA                 1564
ABC     879 Rd     Tampa       FL       5687AB                         546YYY

感谢任何帮助。

attached screenshot

1 个答案:

答案 0 :(得分:1)

使用条件聚合

SELECT
    Name, 
    Address, 
    City, 
    State,
    MAX(CASE WHEN IdType = 'Code1' THEN Id END) AS Code1,
    MAX(CASE WHEN IdType = 'Code2' THEN Id END) AS Code2,
    CASE 
        WHEN MAX(CASE WHEN IdType = 'Code2' THEN Id END) 
            <> MIN(CASE WHEN IdType = 'Code2' THEN Id END)
        THEN MIN(CASE WHEN IdType = 'Code2' THEN Id END) 
    END AS Code2_II,
    MAX(CASE WHEN IdType = 'Code3' THEN Id END) AS Code3
FROM mytable
GROUP BY 
    Name, 
    Address, 
    City, 
    State

MIN/MAX上的Code2技巧使查询可以处理Code2的两个不同值。