按类别划分的SQL行转换为列标题

时间:2016-11-15 21:39:11

标签: sql odbc

需要使用SQL将TBL1转换为TBL2。

TBL1

     Type SubType Value
     ---- ------- -----
     100  100     A
     100  200     B 
     200  100     A
     200  200     C
     300  100     A
     300  300     D
     400  100     A
     400  300     E

TBL2

     Type v100 v200 V300
     ---- ---- ---- ----
     100   A    B
     200   A    C
     300   A        D
     400   A        E

如何在每一行中获得一个新的表,其中所有Subtype作为列标题,以及属于Type的子类型的值。

我正在使用Excel和ODBC将查询字符串发送到DB2服务器

3 个答案:

答案 0 :(得分:2)

不知道你在哪个平台上讨论SQL-Server,Oracle,mysql等?我能给你的唯一答案是Conditional Aggregation

SELECT
    Type
    ,MAX(CASE WHEN SubType = 100 THEN Value END) as v100
    ,MAX(CASE WHEN SubType = 200 THEN Value END) as v200
    ,MAX(CASE WHEN SubType = 300 THEN Value END) as v300
FROM
    Tbl1
GROUP BY
    Type

答案 1 :(得分:2)

您可以使用自我加入

 select t1.Type,  t1.Value as v100,  t2.Value as v200,  t3.Value as v300
 from my_table as t1
 left join my_table as t2 on t1.Type = T2.Type and T2.SubType = 200
 left join my_table as t3 on t1.Type = T3.Type and T3.SubType = 300     
 where t1.Subtype = 100

答案 2 :(得分:2)

以下是Matt答案的动态版本:

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql = 
'SELECT
    Type' + CHAR(10) +
    STUFF((
        SELECT DISTINCT
            '   ,MAX(CASE WHEN SubType = ' + CONVERT(VARCHAR(10), Subtype) + ' THEN Value END) AS '
                + QUOTENAME('v'+ CONVERT(VARCHAR(10), SubType)) + CHAR(10)
        FROM Tbl
        FOR XML PATH('')
    ), 1, 0, '') +
'FROM Tbl
GROUP BY Type;';

PRINT @sql;
EXEC sp_executesql @sql;

这适用于SQL-Server