我正在尝试获取每行的百分比结果,其中该行的分组计数除以所有行的总计,例如:
所以我最终将SUM列作为总计的气球行百分比。
SELECT DATEPART(YEAR, Balloons) AS [Year],
COUNT(Balloons) AS [Balloons],
SUM = (SELECT COUNT(Balloons)
FROM TABLE
WHERE col2 BETWEEN '20000101' AND '20160101'
)
FROM TABLE
WHERE col2 BETWEEN '20000101' AND '20160101'
GROUP BY DATEPART(YEAR, Balloons)
ORDER BY COUNT(Balloons)
答案 0 :(得分:1)
SELECT [Year], [Balloons], ROUND(CAST([Balloons] AS REAL) / CAST([SUM] AS real) * 100 ,3) AS [%] FROM (
SELECT
DATEPART(YEAR, Balloons) AS [Year]
,COUNT(Balloons) AS [Balloons]
,SUM = (SELECT COUNT(Balloons) FROM TABLE WHERE col2 BETWEEN '20000101' AND '20160101')
FROM TABLE
WHERE col2 BETWEEN '20000101' AND '20160101'
GROUP BY DATEPART(YEAR, Balloons)
) AS d
GROUP BY [Balloons], [Year], [SUM]
ORDER BY [Year]
Results
Year Balloons %
1 2010 2 0.009
2 2011 1 0.005
3 2012 1815 8.613
4 2013 5022 23.831
5 2014 7742 36.739
6 2015 6491 30.802