saikoneru1997 / Azure_DataFactory

0 stars 0 forks source link

Lag and lead functions #36

Closed saikoneru1997 closed 1 week ago

saikoneru1997 commented 1 week ago

Image

Image

saikoneru1997 commented 1 day ago
  1. Question: "How would you write a query to get the difference in order dates between consecutive orders for each customer?"

Answer: "You can use the LAG function to get the previous order date and then calculate the difference. For example:

SELECT customer_id, order_date,
 order_date - LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS order_date_diff
FROM orders;

This query will return the difference in order dates between consecutive orders for each customer."

  1. Question: "Can you write a query to get the cumulative sum of order totals for each customer?"

Answer: "You can use the SUM function with the OVER clause to get the cumulative sum. For example:


SELECT customer_id, order_date, order_total,
 SUM(order_total) OVER (PARTITION BY customer_id ORDER BY order_date) AS cumulative_sum
FROM orders;