我有两个表:主表和详细信息
主人:
Id MeterNo readdate
------------------------
1 12345 1/1/2016
2 67891 1/1/2016
细节:
MasterId RDNG_CODE RDNG_VALUE
-------------------------------
1 20 2910
1 21 2711
2 30 8888
2 31 9999
2 32 7777
结果:
MeterNo RDNG_CODE_20 RDNG_CODE_21 RDNG_CODE_30 RDNG_CODE_31 RDNG_CODE_32
------------------------------------------------------------------------------
12345 2910 2711 NULL NULL NULL
67891 NULL NULL 8888 9999 7777
答案 0 :(得分:0)
试试这样:
SET LANGUAGE ENGLISH;
DECLARE @tblMaster TABLE(Id INT,MeterNo INT,readdate DATE);
INSERT INTO @tblMaster VALUES
(1,12345,'1/1/2016')
,(2,67891,'1/1/2016');
DECLARE @tblDetails TABLE(MasterId INT, RDNG_CODE INT,RDNG_VALUE INT);
INSERT INTO @tblDetails VALUES
(1,20,2910)
,(1,21,2711)
,(2,30,8888)
,(2,31,9999)
,(2,32,7777);
SELECT p.*
FROM
(
SELECT m.Id AS MasterID
,m.MeterNo
,'RDNG_CODE_' + CAST(d.RDNG_CODE AS VARCHAR(10)) AS ColumnName
,d.RDNG_VALUE
FROM @tblMaster AS m
INNER JOIN @tblDetails AS d ON m.Id=d.MasterId
) AS tbl
PIVOT
(
MIN(RDNG_VALUE) FOR ColumnName IN(RDNG_CODE_20,RDNG_CODE_21,RDNG_CODE_30,RDNG_CODE_31,RDNG_CODE_32)
)p
答案 1 :(得分:0)
这是PIVOT声明的完美案例
SELECT MasterId,
[20] [RDNG_CODE_20], [21] [RDNG_CODE_21], [30] [RDNG_CODE_30], [31] [RDNG_CODE_31], [32] [RDNG_CODE_32]
FROM
(SELECT MasterId, RDNG_CODE, RDNG_VALUE
FROM @Table) AS SourceTable
PIVOT
(
MAX(RDNG_VALUE)
FOR RDNG_CODE IN ([20], [21], [30], [31], [32])
) AS PivotTable;