我正在使用 SQL Server 2012。我有两个表来保存产品订单。具有接收日期的订单和具有价格和订单 ID fk 的 OrderItem。
我正在尝试编写一个查询来获取日期范围内的所有订单,按日期对它们进行分组,然后对所有订单商品的价格求和以获得该日期所有订单的总数。
我有这个工作。现在我想添加另一列来选择当天总价与 7 天前之间的差额。如果 7 天前没有订单,则该列应为空。
所以目前我有以下查询:
select cast(o.ReceivedDate as date) as OrderDate,
coalesce(count(orderItems.orderId), 0) as Orders,
coalesce(sum(orderItems.Price), 0) as Price
from [Order] o
left outer join (
select o.Id as orderId, sum(ot.Price) as Price
from OrderItem ot
join [Order] o on ot.OrderId = o.Id
where o.ReceivedDate >= @DateFrom and o.ReceivedDate <= @DateTo
group by o.Id
) as orderItems on o.Id = orderItems.orderId
where o.ReceivedDate >= @DateFrom and o.ReceivedDate <= @DateTo
group by cast(o.ReceivedDate as date)
order by cast(o.ReceivedDate as date) desc
那么如何将我的其他列添加到此查询中?我需要做类似的事情:
//pseudo
if o.RecievedDate - 7 exists then orderItems.Price - Price from 7 days ago else null
但我不知道该怎么做?我创建了一个 sqlfiddle 来帮助解释http://sqlfiddle.com/#!6/8b837/1
因此,从我的示例数据中,我想要实现的是这样的结果:
| ORDERDATE | ORDERS | PRICE | DIFF7DAYS |
---------------------------------------------
| 2013-01-25 | 3 | 38 | 28 |
| 2013-01-24 | 1 | 12 | null |
| 2013-01-23 | 1 | 10 | null |
| 2013-01-22 | 1 | 33 | null |
| 2013-01-18 | 1 | 10 | null |
| 2013-01-10 | 1 | 3 | -43 |
| 2013-01-08 | 2 | 11 | null |
| 2013-01-04 | 1 | 1 | null |
| 2013-01-03 | 3 | 46 | null |
如您所见,25 日有 7 天前的订单,因此显示了差异。24 号显示的不是那么空。
任何帮助将非常感激。