SQL - 按星期几返回平均项目数。

时间:2014-11-25 14:29:55

标签: sql sql-server average

我在下面的查询工作正常,并返回发货的项目,总天数和每天的平均项目数。

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

我现在的问题是,我怎样才能获得每周每天的平均出货数量(周一平均值,周二平均值等等),以便最终返回七个结果。我知道每天都有查询的方法,但在一个查询中完成所有操作的有效方法是什么?

我正在为这个项目使用MS SQLServer。

感谢任何人的帮助。

1 个答案:

答案 0 :(得分: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))