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 作为列。
你能帮我做同样的事情吗?
必须使用 PIVOT 你也可以通过使用简单的 case 表达式
来做到这一点
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 |
如果你想要 PIVOT:
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]) SELECT * |
这对我有用
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 |
- 谢谢你的时间。这行得通。你能改变这种方式,使 display、contact 和 ship 在一个变量中作为逗号分隔值吗?例如声明 @Types varchar(max) = \\’display,contact,ship\\’。我将在存储过程中编写此代码,并且此值可能来自单个变量。
1
2 3 4 5 |
SELECT id,name,[display],[contact],[ship]
FROM #b pivot(MAX(VALUE) FOR TYPE IN([display],[contact],[ship])) AS d |
- 仅代码的答案不会为 OP 或任何找到此答案的人提供太多帮助。请更新您的答案并详细说明您认为这回答了 OP 问题的原因。
- 请看如何回答
来源:https://www.codenong.com/47300977/