3

我的头因(愚蠢的)使用尝试而冒烟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%

(请注意总月数0965,因此66%forPurple0's 表示不存在的颜色):

我希望有人梦想 SQL,这是一项容易的任务......

4

2 回答 2

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
于 2010-11-16T15:51:28.820 回答
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

类似的东西......它不会显示本月的前导零,但这真的很重要吗?

于 2010-11-16T15:18:05.490 回答