如何按日期对订单进行分组

时间:2015-11-19 16:34:15

标签: sql sql-server sql-server-2008

我有一个订单明细表,我希望找到每个日期的价格总和,并将其显示为

对于Ex

   count   sum            date 
    5      619.95        2015-11-19
    3      334.97        2015-11-18
    4      734.96        2015-11-18
    5      1129.95       2015-11-18

我已经编写了将countsum作为

的查询
select count(id), sum([price])
from [OrderDetails]
where [date]between '2015-10-29 05:15:00' and '2015-11-09 00:01:00'
group by datepart(day,[date])

但是不能用日期来实现。怎么办呢?

2 个答案:

答案 0 :(得分:3)

您需要在查询的SELECT部分中包含您所分组的内容:

select count(id), sum([price]), datepart(day,[date]) as [date]
from [OrderDetails]
where [date] between '2015-10-29 05:15:00' and '2015-11-09 00:01:00'
group by datepart(day,[date]);

答案 1 :(得分:1)

您的名为date的列似乎同时包含日期和时间组件。我建议将其转换为selectgroup by

的日期
select count(id), sum(price), cast([date] as date) as thedate
from OrderDetails
where [date] between '2015-10-29 05:15:00' and '2015-11-09 00:01:00'
group by cast([date] as date) 
order by thedate;

注意:date是列的名称不佳,因为它是内置类型的名称。