我正在使用SQL Server 2012.我有兩個表來保存產品訂單。包含接收日期和OrderItem的訂單,其中包含價格和訂單ID fk。Sql加入平均值
我有一個查詢按日期對訂單進行分組,並獲取該日期的訂單數量和總價格。我還有一個7天前的訂單數量差異列。
但是,我也希望能夠在過去7天內獲得所有訂單的平均值。
因此,在目前,我有以下查詢:
declare @DateFrom datetime
set @DateFrom = '2012-12-01'
declare @DateTo datetime
set @DateTo = '2013-03-13'
;with orders as (
select
cast(o.ReceivedDate as date) as OrderDate,
count(oi.Id) as Orders,
coalesce(sum(oi.Price), 0) as Price
from OrderItem oi
join [Order] o on oi.OrderId = o.Id
where cast(o.ReceivedDate as date) >= @DateFrom
and cast(o.ReceivedDate as date) <= @DateTo
group by cast(o.ReceivedDate as date)
)
select c1.OrderDate,
c1.Price,
c1.Orders,
c1.Orders - c2.Orders as DIFF7DAYS
from orders c1
left join orders c2 on dateadd(day, -7, c1.OrderDate) = c2.OrderDate
order by c1.OrderDate desc
現在我想補充另一列其獲得的平均訂單在過去的7天。
我已經試過類似:
select c1.OrderDate,
c1.Price,
c1.Orders,
c1.Orders - c2.Orders as DIFF7DAYS,
c3.AverageOrders
from orders c1
left join orders c2 on dateadd(day, -7, c1.OrderDate) = c2.OrderDate
left join (
select OrderDate, avg(Orders) as AverageOrders
from orders
group by OrderDate
) as c3 on c3.OrderDate >= dateadd(day, -7, c1.OrderDate) and c3.OrderDate <= c1.OrderDate and c3.OrderDate = c1.OrderDate
order by c1.OrderDate desc
但似乎並沒有這樣做我什麼。我也嘗試從連接中刪除c3.OrderDate = c1.OrderDate,但後來我得到了影響平均值的重複行。基本上我想添加一列到結果:
select avg(Orders) as AverageOrders
from orders
where OrderDate >= (the current order - 7 days) and OrderDate <= (the current order)
但我不知道如何做到這一點?我創建了一個sqlfiddle幫助解釋http://sqlfiddle.com/#!6/8b837/44
從我想要實現的是我的樣本數據所以結果是這樣的:
| ORDERDATE | ORDERS | PRICE | DIFF7DAYS | AVERAGE |
-------------------------------------------------------
| 2013-01-25 | 7 | 38 | 6 | 2 |
| 2013-01-24 | 2 | 12 | null | 1 |
| 2013-01-23 | 1 | 10 | null | 1 |
| 2013-01-22 | 1 | 33 | null |
| 2013-01-18 | 1 | 10 | null |
| 2013-01-10 | 1 | 3 | -2 |
| 2013-01-08 | 2 | 11 | null |
| 2013-01-04 | 1 | 1 | null |
| 2013-01-03 | 3 | 46 | null |
正如你可以看到,25日的平均的2因爲最後7天(25,24,23,22,18)的四捨五入均值爲2.
我也希望能夠延長這一點,併爲30天以上的平均值添加另一列。
任何幫助將不勝感激。