2014-11-25 44 views
0

我在下面的查詢工作正常,並返回出貨的物品,總天數和平均每天的物品數量。SQL - 按星期天數返回項目的平均數量。

SELECT A.ItemsShipped, A.TotalDays, cast(A.ItemsShipped as float)/cast(A.TotalDays as float) AS  
'Averange items shipped per day' 
FROM(SELECT 
    (SELECT Count(*) 
     FROM PARTNER_WORKORDER 
     WHERE statusNo = 110) 
     AS ItemsShipped, 
    (SELECT DATEDIFF(day, MIN(orderDt),'2013-11-20 00:00:00.000') 
     From PARTNER_WORKORDER) 
     AS TotalDays 
    )A 

我現在已經是一個問題,我怎麼能得到這個返回的每一週的每一天發貨(一般週一,平均週二,等等)項目的平均數量,使其結束返回7個結果。我知道每天都有查詢的方式,但在一個查詢中完成所有操作的有效方式是什麼?

我正在爲此項目使用MS SQLServer。

感謝任何人可以給予的幫助。

回答

0

這應該解決您的問題。我手頭沒有SQL Server實例(所以無法驗證它),但我想你明白了。

WITH OrdersPerDay AS (
    SELECT 
     CAST(orderDt as INTEGER) as OrderDay, 
     COUNT(1) as OrderCount 
    FROM PARTNER_WORKORDER 
    GROUP BY CAST(orderDt as INTEGER) 
    WHERE statusNo = 110 
) 
SELECT 
    DATEPART(dw, CAST(OrderDay as DATETIME)) as WeekDay, 
    AVG(OrderCount) 
FROM OrdersPerDay 
GROUP BY DATEPART(dw, CAST(OrderDay as DATETIME))