sql查询格式化表

时间:2018-02-01 03:55:41

标签: sql sql-server sql-server-2014

这是我的输入表。我正在尝试格式化表格,如下面的输出所示。你能帮我解决一下mssql中的sql查询吗

id    type    code
100    A      k20
100    A      m30
100    B      m30
100    B      m30
101    B      x10
101    B      20
102    A      101

输出表

id    A_CODE      B_CODE
100   k20,m30     m30,m30
101   null        x10,20
102   101         null

2 个答案:

答案 0 :(得分:0)

PIVOT和String Aggregation的许多例子,但这里是两个例子

示例

Select *
 From (
        Select A.ID
              ,Item  = [type]+'_CODE'
              ,Value = Stuff((Select Distinct ',' +[code] From YourTable Where [id]=A.[id] and [type]=A.[type] For XML Path ('')),1,1,'')
         From (Select Distinct [id],[type] from YourTable) A
      ) Src
 Pivot (max(Value) for Item in ([A_CODE],[B_CODE])) Pvt

返回

ID  A_CODE     B_CODE
100 k20,m30    m30
101 NULL       20,x10
102 101        NULL

答案 1 :(得分:0)

试试这个:

SELECT D.id 
 ,STUFF(
        (SELECT ',' + A_Code 
        FROM (
            SELECT id,code A_Code FROM @Tab WHERE type='A'
            )E
        WHERE E.id=D.id FOR XML PATH ('')) , 1, 1, '') A_Code
 ,STUFF(
        (SELECT ',' + B_Code 
        FROM (
            SELECT id,code B_Code FROM @Tab WHERE type='B'
            )E
        WHERE E.id=D.id FOR XML PATH ('')) , 1, 1, '') B_Code
FROM(
    SELECT id
        ,CASE WHEN type='A' THEN code END A_Code
        ,CASE WHEN type='B' THEN code END B_Code
    FROM @Tab
    )D
GROUP BY D.id

<强>输出:

id  A_Code  B_Code
100 k20,m30 m30,m30
101 NULL    x10,20 
102 101     NULL