我的数据集结构如下:
ID | Feedback type | Feedback value
1 Overall rating 5
1 Duration 23.5
1 Representative Steve
2 Overall rating 4
2 Duration 47
2 Representative Jane
基本上,每组三行代表一次交互。我想要的是每个交互的一行,如下所示:
ID | Overall rating | Duration | Representative
1 5 23.5 Steve
2 4 47 Jane
我很难找到制作子查询的正确方法。在Excel中,我只是获取我的ID列表并在原始表中执行vlookup,但我不清楚如何在SQL中执行此操作。感谢您的任何指示!
答案 0 :(得分:0)
这是理想的做法
SELECT *
FROM TableName
PIVOT(MAX([Feedback value])
FOR [Feedback type] IN ([Overall rating], [Duration], [Representative])
) AS PVTTable
但是,用户无法使用pivot,因此也可以使用
SELECT [ID],
MAX(CASE WHEN [Feedback type] = 'Overall rating'
THEN [Feedback value]
ELSE '' END) AS 'Overall Rating',
MAX(CASE WHEN [Feedback type] = 'Duration'
THEN [Feedback value]
ELSE '' END) AS 'Duration',
MAX(CASE WHEN [Feedback type] = 'Representative'
THEN [Feedback value]
ELSE '' END) AS 'Representative'
FROM TableName
GROUP BY [ID]
答案 1 :(得分:0)
我会采取不同的方式:
SELECT T0.ID, T0.[Overall Rating], T1.Duration, T2.Representative
FROM (SELECT ID, [Feedback Value] AS 'Overall Rating' where [Feedback Type] = 'Overall Rating' FROM TableName) T0
LEFT JOIN (SELECT ID, [Feedback Value] AS 'Duration' where [Feedback Type] = 'Duration' FROM TableName) T1 ON T0.id = T1.id
LEFT JOIN (SELECT ID, [Feedback Value] AS 'Representative' where [Feedback Type] = 'Representative' FROM TableName) T2 ON T0.id = T2.id
基本上,我正在创建"子表"查询 - 每个评级,持续时间和代表。因为它们都链接到相同的ID,所以您可以创建表格然后加入它们。当然,如果它是一个大型表,这不是创建此查询的最有效方法,但对于像您的示例那样小的东西,它应该可以正常工作。