表@Table1
包含结果集,需要将其转换为下面提到的Output
格式。
DECLARE @Table1 TABLE
(
DomainID INT ,
AttributeName VARCHAR(20) ,
UOM VARCHAR(10) ,
Quantity DECIMAL(14, 2)
);
INSERT INTO @Table1
( DomainID, AttributeName, UOM, Quantity )
VALUES ( 1, 'CPU_Usage', 'RPM', 19.86 ),
( 1, 'Bandwidth', 'kbps', 68820.00 ),
( 1, 'Storage', 'Mb', 116.63 ),
( 2, 'CPU_Usage', 'RPM', 27.46 ),
( 2, 'Bandwidth', 'kbps', 79970.00 ),
( 2, 'Storage', 'Mb', 157.05 ),
( 3, 'CPU_Usage', 'RPM', 3.27 ),
( 3, 'Bandwidth', 'kbps', 5924.00 ),
( 3, 'Storage', 'Mb', 96.66 );
SELECT *
FROM @Table1;
需要转动的表格数据。
DomainID AttributeName UOM Quantity
1 CPU_Usage RPM 19.86
1 Bandwidth kbps 68820.00
1 Storage Mb 116.63
2 CPU_Usage RPM 27.46
2 Bandwidth kbps 79970.00
2 Storage Mb 157.05
3 CPU Usage RPM 3.27
3 Bandwidth kbps 5924.00
3 Storage Mb 96.66
3 Storage Mb 96.66
必填Output
答案 0 :(得分:2)
调用条件聚合进行救援:
DECLARE @Table1 TABLE
(
DomainID INT ,
AttributeName VARCHAR(20) ,
UOM VARCHAR(10) ,
Quantity DECIMAL(14, 2)
);
INSERT INTO @Table1
( DomainID, AttributeName, UOM, Quantity )
VALUES ( 1, 'CPU_Usage', 'RPM', 19.86 ),
( 1, 'Bandwidth', 'kbps', 68820.00 ),
( 1, 'Storage', 'Mb', 116.63 ),
( 2, 'CPU_Usage', 'RPM', 27.46 ),
( 2, 'Bandwidth', 'kbps', 79970.00 ),
( 2, 'Storage', 'Mb', 157.05 ),
( 3, 'CPU_Usage', 'RPM', 3.27 ),
( 3, 'Bandwidth', 'kbps', 5924.00 ),
( 3, 'Storage', 'Mb', 96.66 );
SELECT DomainID
, MAX(CASE WHEN AttributeName='CPU_Usage' THEN UOM END) AS CPU_UOM
, MAX(CASE WHEN AttributeName='CPU_Usage' THEN Quantity END) AS CPUQuantity
, MAX(CASE WHEN AttributeName='Bandwidth' THEN UOM END) AS Bandwidth_UOM
, MAX(CASE WHEN AttributeName='Bandwidth' THEN Quantity END) AS BandwidthQuantity
, MAX(CASE WHEN AttributeName='Storage' THEN UOM END) AS Storage_UOM
, MAX(CASE WHEN AttributeName='Storage' THEN Quantity END) AS StorageQuantity
FROM @Table1
GROUP BY DomainID;
答案 1 :(得分:0)
SELECT PivotTable.DomainID ,
PivotTable.[CPU_Usage(RPM)] ,
PivotTable.[Bandwidth(kbps)] ,
PivotTable.[Storage(Mb)]
FROM ( SELECT DomainID ,
AttributeName + '(' + UOM + ')' AS Attribute ,
Quantity
FROM @Table1
) src PIVOT
( MAX(Quantity) FOR Attribute IN ( [CPU_Usage(RPM)], [Bandwidth(kbps)],
[Storage(Mb)] ) ) PivotTable;