我从另一个表中获得了结果集。 父表上的QUERY:
SELECT Type, COUNT(Result) AS [Counts]
FROM ParentTable
GROUP BY Type
结果:
===============
TYPE | Counts
===============
Type1 | 43
Type2 | 13
Type3 | 16
我需要输出格式如下......
===============================
TYPE | COUNTs | [Percentage]
===============================
Type1 | 43 | 59.72
Type2 | 13 | 18.06
Type3 | 16 | 22.22
答案 0 :(得分:1)
大多数数据库都支持ANSI标准窗口函数。你可以这样做:
SELECT Type, COUNT(Result) AS [Counts],
COUNT(Result) * 1.0 / SUM(COUNT(Result)) OVER () as ratio
FROM ParentTable
GROUP BY Type ;
答案 1 :(得分:0)
你可以试试;我只将COUNT更改为SUM以简化答案。
declare @ParentTable as table (Type char(5) , Result int)
INSERT @ParentTable (Type, Result) values
('Type1' , 43 ),
('Type2' , 13 ),
('Type3' , 16 )
SELECT Type,
SUM(Result) OVER ( PARTITION BY Type) AS [Counts] ,
Round(Cast(SUM(Result) OVER ( PARTITION BY Type) as float) / Cast(SUM(Result) OVER (PARTITION BY 1) as float) * 100. ,2) Percentage
FROM @ParentTable
Type Counts Percentage
----- ----------- ----------------------
Type1 43 59.72
Type2 13 18.06
Type3 16 22.22