按周分组,获得一周的第一天,按工作日进行调整

时间:2014-06-25 00:07:38

标签: sql sql-server

我需要进行一个查询,以显示每个客户每周订购的每个项目/单位组合的数量(按周分组),同时显示一周的第一天,并且还显示该周每天订购的数量(按工作日调整)。到目前为止,我有这个,但我不确定如何按周分组。

SELECT customer_name, item_code, item_desc,  unit, delivery_date, [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday]
FROM (
    SELECT customer_name, item_code , item_desc , unit, delivery_date, DATENAME(dw, delivery_date) AS DayWeek, qty
    FROM order_items oi inner join orders on localID = local_order_id
    ) AS ordersItems
    pivot (
        SUM(qty) FOR DayWeek IN ([Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday])
    ) AS pvt

1 个答案:

答案 0 :(得分:1)

以下查询按客户/项目/单位/周#组合分组。它返回订单总数以及按星期几细分的订单数。 CASE语句与SUM函数一起使用以获取一周中每一天的订单总数

编辑:修改了按周开始日期分组的查询(而不是之前的周#)

SELECT customer_name, item_code, item_desc, unit, 
CASE SIGN(7-(DATEPART(dw, action)+2))
  WHEN -1 THEN CAST(DATEADD(dd, 7-(DATEPART(dw, action)+2), action) AS DATE)
  WHEN 0 THEN CAST(action AS DATE)
  WHEN 1 THEN CAST(DATEADD(dd, -(DATEPART(dw, action)+2), action) AS DATE)
END Week_Starting_Friday
SUM(qty) Total_Orders, 
SUM(
    CASE DATENAME(dw, delivery_date) WHEN 'Monday' THEN qty ELSE 0 END
) [Monday],
SUM(
    CASE DATENAME(dw, delivery_date) WHEN 'Tuesday' THEN qty ELSE 0 END
) [Tuesday],
SUM(
    CASE DATENAME(dw, delivery_date) WHEN 'Wednesday' THEN qty ELSE 0 END
) [Wednesday],
SUM(
    CASE DATENAME(dw, delivery_date) WHEN 'Thursday' THEN qty ELSE 0 END
) [Thursday],
SUM(
    CASE DATENAME(dw, delivery_date) WHEN 'Friday' THEN qty ELSE 0 END
) [Friday],
SUM(
    CASE DATENAME(dw, delivery_date) WHEN 'Saturday' THEN qty ELSE 0 END
) [Saturday],
SUM(
    CASE DATENAME(dw, delivery_date) WHEN 'Sunday' THEN qty ELSE 0 END
) [Sunday]
FROM order_items oi inner join orders on localID = local_order_id
GROUP BY customer_name, item_code, item_desc, unit, 
CASE SIGN(7-(DATEPART(dw, action)+2))
  WHEN -1 THEN CAST(DATEADD(dd, 7-(DATEPART(dw, action)+2), action) AS DATE)
  WHEN 0 THEN CAST(action AS DATE)
  WHEN 1 THEN CAST(DATEADD(dd, -(DATEPART(dw, action)+2), action) AS DATE)
END
ORDER BY 5, customer_name, item_code, item_desc, unit;

<强>参考

  1. CASE statement on MSDN
  2. DATENAME on MSDN