SQL Server Pivot以百分比而非值的形式显示,并添加总行和列

时间:2018-10-29 15:26:04

标签: sql sql-server

我有一些代码可以帮助我:

SELECT [U C], [M] AS EE, [F] AS LL
FROM   
(SELECT [U N], f_k, [U C]  
FROM [MH2] 
WHERE [U C] IN ('I', 'E', 'T')) p  
PIVOT (COUNT ([U N]) 
 FOR f_k IN ([M], [F])) AS pvt  
ORDER BY pvt.[U C]

输出:

U C     EE      LL
E       509762  412358
I       16440   1138538
T       197     8753

但是我希望这是一个这样的百分比,并具有总计的行和列:

U C   EE        LL      Total
E     24.44%    19.77%  44.20%
I     0.79%     54.58%  55.37%
T     0.01%     0.42%   0.43%
Total 25.23%    74.77%  100.00%
  

使用@ Gordon Linoff的答案的变体形式进行编辑解决。

SELECT COALESCE([U C], 'Total') [U C],
SUM(CASE WHEN f_k = 'F' THEN 1 ELSE 0 END) * 100.0 / cnt LL,
SUM(CASE WHEN f_k = 'M' THEN 1 ELSE 0 END) * 100.0 / cnt EE,
COUNT(*) * 100.0 / cnt Total
FROM (SELECT mh2.*, count(*) over () cnt
FROM mh2
WHERE [U C] IN ('I', 'E', 'T') 
AND f_k IN ('F', 'M')) mh2
GROUP BY GROUPING SETS (([U C], cnt))
UNION ALL
SELECT 'Total', SUM(a.LL), SUM(a.EE), ROUND(SUM(a.Total),2)
FROM(
SELECT COALESCE([U C], 'Total') [U C],
SUM(CASE WHEN f_k = 'F' THEN 1 ELSE 0 END) * 100.0 / cnt LL,
SUM(CASE WHEN f_k = 'M' THEN 1 ELSE 0 END) * 100.0 / cnt EE,
COUNT(*) * 100.0 / cnt Total
FROM (SELECT mh2.*, count(*) over () cnt
FROM mh2  
WHERE [U C] IN ('I', 'E', 'T') 
AND f_k IN ('F', 'M')) mh2
GROUP BY GROUPING SETS (([U C], cnt))) a

1 个答案:

答案 0 :(得分:1)

我发现条件聚合要简单得多:

select coalesce([U C], 'total') as [U C],
       sum( case when fk = 'F' then 1 else 0 end) * 100.0 / cnt as EE,
       sum( case when fk = 'M' then 1 else 0 end) * 100.0 / cnt as LL,
       count(*) * 100.0 / cnt as total
from (select mh2.*, count(*) over () as cnt
      from mh2 
      where [U C] in ('I', 'E', 'T') and
            fk in ('F', 'M')
     ) mh2
group by grouping sets ( ([U C], cnt), (cnt) )