Pivoting the data
这是我的 SQL 语句
1 2 3 | SELECT id , name, TYPE, VALUE FROM table1 a INNER JOIN table2 b ON a.id = b.id WHERE b.type IN ('display','contact','ship') |
产生以下结果
1 2 3 4 5 6 7 | ID name TYPE VALUE 5 test display display1 5 test contact contact1 5 test ship ship1 6 test2 display display2 6 test2 contact contact2 6 test2 ship ship2 |
我需要得到像这样的旋转格式的结果
1 2 3 | id name display contact ship 5 test display1 contact1 ship1 6 test2 display2 contact2 ship2 |
我尝试了这个解决方案:https://stackoverflow.com/a/6849706/2645738,但它给了我相同的结果(每个数据 3 行)。就像我需要按 id 和 name 分组,但不知道如何将 display、contact、ship 作为列。
你能帮我做同样的事情吗?
必须使用
来做到这一点
1 2 3 4 5 6 | SELECT ID, Name, MAX(CASE([TYPE]) WHEN 'display' THEN VALUE END) [display], MAX(CASE([TYPE]) WHEN 'contact' THEN VALUE END) [contact], MAX(CASE([TYPE]) WHEN 'ship' THEN VALUE END) [ship] FROM <table> GROUP BY ID, Name |
结果:
1 2 3 | ID Name display contact ship 5 test display1 contact1 ship1 6 test2 display2 contact2 ship2 |
如果你想要
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | DECLARE @DataSource TABLE ( [id] TINYINT ,[name] VARCHAR(12) ,[TYPE] VARCHAR(12) ,[VALUE] VARCHAR(12) ); INSERT INTO @DataSource ([id], [name], [TYPE], [VALUE]) VALUES (5, 'test', 'display', 'display1') ,(5, 'test', 'contact', 'contact1') ,(5, 'test', 'ship', 'ship1') ,(6, 'test2', 'display', 'display2') ,(6, 'test2', 'contact', 'contact2') ,(6, 'test2', 'ship', 'ship2'); SELECT * FROM @DataSource PIVOT ( MAX([VALUE]) FOR [TYPE] IN ([display], [contact], [ship]) ) PVT; |
这对我有用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | WITH T AS ( SELECT id , name, TYPE, VALUE FROM table1 a INNER JOIN table2 b ON a.id = b.id WHERE b.type IN ('display','contact','ship') ) SELECT * FROM T PIVOT ( MAX([VALUE]) FOR [TYPE] IN ( [display],[Contact],[Ship] ) )PVT |
检查 SQLFiddle
这个查询应该会给你想要的结果:
1 2 3 4 5 6 7 8 | SELECT a.id , a.name, MAX(CASE WHEN b.type = 'display' THEN VALUE END) AS display, MAX(CASE WHEN b.type = 'contact' THEN VALUE END) AS contact, MAX(CASE WHEN b.type = 'ship' THEN VALUE END) AS ship FROM table1 a INNER JOIN table2 b ON a.id = b.id WHERE b.type IN ('display','contact','ship') GROUP BY a.id, a.name |
1 2 3 4 5 | SELECT id,name,[display],[contact],[ship] FROM #b pivot(MAX(VALUE) FOR TYPE IN([display],[contact],[ship])) AS d |