我整天都在研究一个“简单”的问题,这让我很生气。我确定我错过了一些明显的东西;但是没有多少搜索能帮助我。
我有一行数据表,如; (TABLE_1)
Person_1 Person_2 Person_3
PersonID ABC DEF GHI
但是我需要用另一个表中的值替换引用但是与ID列匹配,例如; (TABLE_2)
PersonID Work_Done
LMN 298
GHI 187
ABC 872
XYZ 468
DEF 512
因此返回;
Person_1 Person_2 Person_3
Work_Done 872 512 187
我使用的是Microsoft SQL Server企业版V8.00.2039,我无法控制源表。
任何帮助(甚至只是谷歌的想法)都会非常感激。
用于生成示例表的SQL;
-- Table_1
SELECT
'ABC' AS Person_1,
'DEF' AS Person_2,
'GHI' AS Person_3
;
-- Table_2
SELECT 'LMN' AS Person_ID, 298 AS Work_Done
UNION ALL
SELECT 'GHI' AS Person_ID, 187 AS Work_Done
UNION ALL
SELECT 'ABC' AS Person_ID, 872 AS Work_Done
UNION ALL
SELECT 'XYZ' AS Person_ID, 468 AS Work_Done
UNION ALL
SELECT 'DEF' AS Person_ID, 512 AS Work_Done
;
--Returning
SELECT
'872' AS Person_1,
'512' AS Person_2,
'187' AS Person_3;
答案 0 :(得分:1)
由于您无法更改设计,因此以下是检索所需内容的代码:
SELECT Person_1 = a.Work_Done
, Person_2 = b.Work_Done
, Person_3 = c.Work_Done
FROM Table1 t
JOIN Table2 a ON t.Person_1 = a.Person_ID
JOIN Table2 b ON t.Person_2 = b.Person_ID
JOIN Table2 c ON t.Person_3 = c.Person_ID
多个连接到同一个表的别名(表2)
答案 1 :(得分:0)
SELECT *
FROM
(
SELECT unpvt.Person_Type, b.Work_Done
FROM Table_1 a
UNPIVOT ( Person_ID FOR Person_Type IN (a.[Person_1], a.[Person_2], a.[Person_3]) ) unpvt
JOIN Table_2 b ON unpvt.Person_ID = b.Person_ID
) c
PIVOT ( MAX(c.Work_Done) FOR c.Person_Type IN ([Person_1], [Person_2], [Person_3]) ) pvt
答案 2 :(得分:0)
DO PIVOT
http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
请注意,如果您想要使用不同的组合,则需要使用嵌入式SQL和EXEC @sql
请注意FOR FOR Person_ID IN([ABC],[DEF],[LMN],[GHI],[XYZ])
当你做@sql时,[ABC]是你需要小心'撇号'的表的列。
SELECT
*
FROM(
SELECT 'LMN' AS Person_ID, 298 AS Work_Done
UNION ALL
SELECT 'GHI' AS Person_ID, 187 AS Work_Done
UNION ALL
SELECT 'ABC' AS Person_ID, 872 AS Work_Done
UNION ALL
SELECT 'XYZ' AS Person_ID, 468 AS Work_Done
UNION ALL
SELECT 'DEF' AS Person_ID, 512 AS Work_Done
) as datasourcetable
PIVOT
(
SUM(Work_Done )
FOR Person_ID IN ([ABC], [DEF],[LMN],[GHI],[XYZ])
) AS PivotTable;