简体   繁体   中英

group by week, get first day of week, pivot by weekday

I need to make a query that will show how much of each item/unit combination each customer ordered each week (group by week) while showing the first day the week, and also showing the quantity ordered each day of that week (pivot by weekday). So far i have this, but I'm not sure how to group this by week.

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

The following query groups by customer/item/unit/week# combination. It returns the total number of orders as well as the # of orders broken down by the day of the week. The CASE statement is used along with the SUM function to get the total number of orders for each day of the week

EDIT : Revised query to group by Week Starting Date (instead of week # previously)

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;

References :

  1. CASE statement on MSDN
  2. DATENAME on MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM