0

在 SQL Server 中苦苦挣扎,有什么想法吗?给定这些数据(ID 是一个 INT,其余的是 BIT):

------------------------------------------
ID   Type1   Type2   AttrA   AttrB   AttrC
------------------------------------------
1    1       0       1       0       0
2    1       0       1       0       0
3    1       1       0       1       1
4    0       1       1       1       0
5    1       1       1       1       0

我想制作这份报告:

---------------------------------------------------------
Attr    NumOfType1   PctOfType1   NumOfType2   PctOfType2
---------------------------------------------------------
AttrA   3            75%          2            67%
AttrB   2            50%          3            100%
AttrC   1            25%          1            33%
Total   4            N/A          3            N/A

谢谢!

吉姆

4

1 回答 1

2
;WITH YourBaseTable AS
(
SELECT 1 ID, 1 Type1,0 Type2, 1 AttrA, 0 AttrB, 0 AttrC UNION ALL
SELECT 2 ID, 1 Type1,0 Type2, 1 AttrA, 0 AttrB, 0 AttrC  UNION ALL
SELECT 3,1,1,0,1,1 UNION ALL
SELECT 4,0,1,1,1,0 UNION ALL
SELECT 5,1,1,1,1,0 
), T AS
(
SELECT *, 1 AS Total
FROM YourBaseTable
)
SELECT 
Attr,
 COUNT(CASE WHEN VALUE = 1 AND Type1 = 1 THEN 1 END) NumOfType1, 
 CASE WHEN Attr <> 'Total' THEN 100 * CAST(COUNT(CASE WHEN VALUE = 1 AND Type1 = 1 THEN 1 END) AS FLOAT)/COUNT(CASE WHEN Type1 = 1 THEN 1 END) END PctOfType1, 
 COUNT(CASE WHEN VALUE = 1 AND Type2 = 1 THEN 1 END) NumOfType2,
 CASE WHEN Attr <> 'Total' THEN 100 * CAST(COUNT(CASE WHEN VALUE = 1 AND Type2 = 1 THEN 1 END) AS FLOAT)/COUNT(CASE WHEN Type2 = 1 THEN 1 END) END PctOfType2
FROM T
UNPIVOT
(VALUE FOR Attr IN (AttrA, AttrB,AttrC, Total)) AS unpvt
GROUP BY Attr
于 2010-12-03T15:18:59.447 回答