我在sql中有一个包含以下数据的表,
Bus_Type Invalid_Counts Valid_Counts Percentage
---------------------------------------------------------
General 721 1339 53.85
Inquiry 243 9301 2.61
Firm 553 1207 45.82
我想使用pivot并以下列格式获取数据,
Cols General Inquiry Firm
-------------------------------------------
Invalid_Counts 721 243 553
Valid_Counts 1339 9301 1207
Percentage 53.85 2.61 45.82
这是我对pivot的查询,
select * from
(select Bus_Type, Invalid_Counts, Valid_Counts, Percentage from #temp) a
pivot(max(Invalid_Counts) for Bus_Type in (General, Inquiry, Firm)) pv
给了我以下结果,这不是我想要的,
Valid_Counts Percentage Firm General Inquiry
-----------------------------------------------------------
1339 53.85 NULL 243 NULL
9301 2.61 NULL NULL 553
1207 45.82 721 NULL NULL
任何想法都将受到赞赏和帮助。
感谢。
答案 0 :(得分:1)
DECLARE @TABLE TABLE (Bus_Type VARCHAR(100), Invalid_Counts INT
,Valid_Counts INT,Percentage DECIMAL(10,2))
INSERT INTO @TABLE VALUES
('General', 721 , 1339 , 53.85 ),
('Inquiry', 243 , 9301 , 2.61 ),
('Firm' , 553 , 1207 , 45.82 )
;WITH CTE AS
(
SELECT Bus_Type
,CAST(Invalid_Counts AS DECIMAL(10,2)) AS Invalid_Counts
,CAST(Valid_Counts AS DECIMAL(10,2)) AS Valid_Counts
,CAST(Percentage AS DECIMAL(10,2)) AS Percentage
FROM @TABLE
)
SELECT * FROM CTE
UNPIVOT ( Vals FOR Cols IN (Invalid_Counts, Valid_Counts , Percentage))up
PIVOT (SUM(Vals) FOR Bus_Type IN (General, Inquiry , Firm))P
╔════════════════╦═════════╦═════════╦═════════╗
║ Cols ║ General ║ Inquiry ║ Firm ║
╠════════════════╬═════════╬═════════╬═════════╣
║ Invalid_Counts ║ 721.00 ║ 243.00 ║ 553.00 ║
║ Percentage ║ 53.85 ║ 2.61 ║ 45.82 ║
║ Valid_Counts ║ 1339.00 ║ 9301.00 ║ 1207.00 ║
╚════════════════╩═════════╩═════════╩═════════╝