分组与案例陈述?

时间:2014-07-21 23:16:30

标签: sql ms-access

我需要找到数字 3天范围内的订单总和。所以想象一下像这样的表

订单 日期
300 1/5/2015
200 1/6/2015
150 1/7/2015
250 1/5/2015
400 1/4/2015
350 1/3/2015
50 1/2/2015
100 1/8/2015

所以我想创建一个Group by Clause,它将具有相同月份,年份和日期的任何日期分组为1-3或4-6,7-9等等,直到我达到30天为止。< / p>

似乎我想要做的是为包含某种类型的循环的分组创建一个案例,但我不确定这是否是最佳方式,或者是否甚至可以将它们组合起来。

替代方法可能是创建一个案例陈述,创建一个新列,分配组号,然后按该号码,月份和年份进行分组。

不幸的是我从未使用过case语句,因此我不确定哪种方法最好或者如何执行它们,尤其是循环。

编辑:我正在使用Access,所以看起来我将使用 IIF 而不是Case

2 个答案:

答案 0 :(得分:2)

考虑Partition Function和交叉表,例如:

TRANSFORM Sum(Calendar.Order) AS SumOfOrder
SELECT Month([CalDate]) AS TheMonth, Partition(Day([Caldate]),1,31,3) AS DayGroup
FROM Calendar
GROUP BY Month([CalDate]), Partition(Day([Caldate]),1,31,3)
PIVOT Year([CalDate]);

顺便说一句,我希望您没有将字段/列命名为Date。

答案 1 :(得分:0)

以下内容如何:

订单数量

select      year([Date]) as yr,
            month([Date]) as monthofyr,
            sum(iif((day([Date])>=1) and (day([Date])<=3),1,0)) as days1to3,
            sum(iif((day([Date])>=4) and (day([Date])<=6),1,0)) as days4to6,
            sum(iif((day([Date])>=7) and (day([Date])<=9),1,0)) as days7to9,
            sum(iif((day([Date])>=10) and (day([Date])<=12),1,0)) as days10to12,
            sum(iif((day([Date])>=13) and (day([Date])<=15),1,0)) as days13to15,
            sum(iif((day([Date])>=16) and (day([Date])<=18),1,0)) as days16to18,
            sum(iif((day([Date])>=19) and (day([Date])<=21),1,0)) as days19to21,
            sum(iif((day([Date])>=22) and (day([Date])<=24),1,0)) as days22to24,
            sum(iif((day([Date])>=25) and (day([Date])<=27),1,0)) as days25to27,
            sum(iif((day([Date])>=28) and (day([Date])<=31),1,0)) as days28to31
from        tbl
where       [Date] between x and y
group by    year([Date]),
            month([Date])

将x和y替换为您的日期范围。

最后一组是当月的第28天到第31天,所以它可能包含4天的订单,包含31天的月份。

以上是一些订单。

如果您想要订单金额的总和:

订单金额的总和

select      year([Date]) as yr,
            month([Date]) as monthofyr,
            sum(iif((day([Date])>=1) and (day([Date])<=3),order,0)) as days1to3,
            sum(iif((day([Date])>=4) and (day([Date])<=6),order,0)) as days4to6,
            sum(iif((day([Date])>=7) and (day([Date])<=9),order,0)) as days7to9,
            sum(iif((day([Date])>=10) and (day([Date])<=12),order,0)) as days10to12,
            sum(iif((day([Date])>=13) and (day([Date])<=15),order,0)) as days13to15,
            sum(iif((day([Date])>=16) and (day([Date])<=18),order,0)) as days16to18,
            sum(iif((day([Date])>=19) and (day([Date])<=21),order,0)) as days19to21,
            sum(iif((day([Date])>=22) and (day([Date])<=24),order,0)) as days22to24,
            sum(iif((day([Date])>=25) and (day([Date])<=27),order,0)) as days25to27,
            sum(iif((day([Date])>=28) and (day([Date])<=31),order,0)) as days28to31
from        tbl
where       [Date] between x and y
group by    year([Date]),
            month([Date])