SQL每月加入和每月总百分比

时间:2010-11-16 15:09:59

标签: sql sql-server-2008 subtotal

我的头脑是从(愚蠢)尝试使用JOINWITHGROUP 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%的{​​{1}}以及Purple的{​​{1}}不存在的颜色):

我希望有人在SQL中做梦,这是一件容易的事......

2 个答案:

答案 0 :(得分:3)

这有效,但有以下警告:

  • 日期时间值必须仅为日期
  • 仅列出有任何数据的月份
  • 我列出了该月的第一天,以防您有超过数年的数据(我假设您不希望从2009年1月开始汇总数据与2010年1月的数据)
  • 我留给您的精确百分比列格式详细信息,我必须重新开始工作

代码:

;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

答案 1 :(得分:2)

SELECT
    [Month],
    [Name],
    [Count],
    CASE WHEN TotalMonth=0 THEN 'INF' ELSE cast(round([Count],0)*100.0/TotalMonth,0) as int) + '%' END as [Percentage]
FROM 
(
SELECT 
    [Months].[Month] as [Month],
    CN.[Name],
    isnull(CC.[Count],0) as [Count],
    (SELECT SUM([Count]) FROM ColorCount WHERE 
            datepart(month,[Date])=datepart(month,CC.[Date])
     ) as [TotalMonth]
FROM (SELECT DISTINCT datepart(month,[Date]) as [Month] FROM ColorCount) [Months]
LEFT JOIN ColorName CN ON [Months].[Month]=datepart(month,CC.[Date])
LEFT JOIN ColorCount CC ON CN.ColorID=CC.ColorID
) AS tbl1
ORDER BY
    [Month] ASC,
    [Name] ASC

像这样...... 它不会显示当月的前导零,但它真的重要吗?