我的头在抽烟,这是(愚蠢的)尝试使用JOIN
,WITH
和GROUP BY
为我的常见情况提供解决方案的-我只是无法将自己的头缠住。让我立即向您抛出示例:
我有两个表(ColorCount和Colorname):
ColorCount:
ColorID Count Date
1 42 2010-09-07
1 1 2010-09-08
2 22 2010-09-14
1 20 2010-10-10
3 4 2010-10-14
ColorName:
ColorID Name
1 Purple
2 Green
3 Yellow
4 Red
现在,我要做的就是将ColorName表加入到ColorCount表中,总结每月的所有颜色计数,然后从每月总计中计算每个计数的百分比。表格胜于文字:
Output:
Month Color Count Percentage
09 Purple 43 66%
09 Green 22 33%
09 Yellow 0 0%
09 Red 0 0%
10 Purple 20 83%
10 Green 0 0%
10 Yellow 4 16%
10 Red 0 0%
(请注意,每月的总数
09
是65
,因此66%
表示Purple
,还有0
表示不存在的颜色):我希望有人梦想着使用SQL,这是一件容易的事...
最佳答案
这适用于以下注意事项:
码:
;with cte (ColorId, Mth, TotalCount)
as (select
ColorId
,dateadd(dd, -datepart(dd, Date) + 1, Date) Mth
,sum(Count) TotalCount
from ColorCount
group by ColorId, dateadd(dd, -datepart(dd, Date) + 1, Date))
select
AllMonths.Mth [Month]
,cn.Name
,isnull(AggData.TotalCount, 0) [Count]
,isnull(100 * AggData.TotalCount / sum(AggData.TotalCount * 1.00) over (partition by AllMonths.Mth), 0) Percentage
from (select distinct Mth from cte) AllMonths
cross join ColorName cn
left outer join cte AggData
on AggData.ColorId = cn.ColorId
and AggData.Mth = AllMonths.Mth
order by AllMonths.Mth, cn.ColorId
关于sql - SQL每月加入和每月总百分比,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4195566/