SQL按日期排序的订单总和

时间:2015-08-20 11:45:50

标签: sql

我应该知道这一点,但由于某种原因让我难过。

这个简单的代码按天输出所有订单

USE [K.1]
Select CreatedAt,Identifier,RoundedPriceSum from StarOrder
where SiteID = 1
and OrderType <>2
and CreatedAt between '2015/01/01' and '2015/08/20'

CreatedAt是一个日期,Identifier是唯一的订单ID和RoundedPriceSum订单的总和。

是否可以修改代码以提供每天的RoundedPriceSum _

2 个答案:

答案 0 :(得分:2)

使用GROUP BY

Select cast(CreatedAt as date) as CreatedDay, SUM(RoundedPriceSum)
from StarOrder so
where SiteID = 1 and OrderType <> 2 and
      CreatedAt >= '2015-01-01' and
      CreatedAt < '2015/08/20'
group by cast(CreatedAt as date)
order by CreatedDay;

有关查询更改的说明:

  • 将日期更改为ISO标准YYYY-MM-DD格式。
  • BETWEEN替换为>=<。这对于有时间的日期更有效。
  • 使用cast(as date)删除时间组件。
  • 添加了ORDER BY,因此结果按日排序。

答案 1 :(得分:1)

select s.CreatedAt,s.Identifier,x.tot
from StarOrder s
join 
(select CreatedAt,sum(RoundedPriceSum) as tot
from StarOrder
where SiteID = 1
and OrderType <>2
and CreatedAt between '2015/01/01' and '2015/08/20'
group by createdat) x
on x.createdat = s.createdat
where SiteID = 1
and OrderType <>2
and s.CreatedAt between '2015/01/01' and '2015/08/20'