write a mssql query for below use case We are displaying the date from our calendar\days…
- User
write a mssql query for below use case We are displaying the date from our calendar_days table which is all possible dates within a range. We specify the year, month, and dayname of that date.
We then show the number of orders for that date, which we used the DISTINCT keyword to avoid duplicate orders from joining to the order_line table.
We added a count for the number of books, and sum of the total price.
We then used an analytic function of SUM and COUNT to find the running total of the number of books for the month.
We then added a LAG function to see the number of books sold on the same day in the previous week.
We selected from the calendar_days table, and performed a LEFT JOIN on the cust_order and order_line tables, so dates with no orders are still shown.
The data is then grouped by the non-aggregate columns we selected, which are the date columns.
Finally, we order by the calendar_date to show earlier dates at the top.
- Assistantcode
SELECT calendar_days.year, calendar_days.month, calendar_days.dayname, calendar_days.calendar_date, COUNT(DISTINCT cust_order.order_id) as num_orders, SUM(order_line.quantity) as num_books, SUM(order_line.quantity * order_line.price) as total_price, SUM(SUM(order_line.quantity)) OVER (PARTITION BY calendar_days.month ORDER BY calendar_days.calendar_date) as running_total_books, LAG(SUM(order_line.quantity)) OVER (PARTITION BY calendar_days.dayname ORDER BY calendar_days.calendar_date) as prev_week_books FROM calendar_days LEFT JOIN cust_order ON calendar_days.calendar_date = cust_order.order_date LEFT JOIN order_line ON cust_order.order_id = order_line.order_id GROUP BY calendar_days.year, calendar_days.month, calendar_days.dayname, calendar_days.calendar_date ORDER BY calendar_days.calendar_date