मुख्य सामग्री पर जाएं
eLearner.app
मॉड्यूल 13 · पाठ 4 का 4पाठ्यक्रम में 52/57~12 min
मॉड्यूल पाठ (4/4)

शिफ्ट: LAG और लीड

Shifts: LAG and LEAD

In sequential and time-based data, you often need to compare the current row with the one from the previous day. In "standard" SQL, doing so requires very dangerous (and very slow) self-joins.

The LAG() (previous row) and LEAD() (next row) functions solve exactly this problem with extreme agility and elegance.

Looking to the Past and the Future

SQL
SELECT
  created_at,
  total_amount,
  LAG(total_amount) OVER(ORDER BY created_at) AS importo_ordine_precedente
FROM orders;

In the example, each row will conveniently carry the amount produced by the same table, shifted forward by one row (backwards in time). We can easily subtract total_amount - LAG(...) to compute the difference or month-over-month percentage changes!

Likewise, LEAD() will pull the value from the row right below the current one.

व्यायाम#sql.m13.l4.e1
प्रयास: 0लोड हो रहा है...

From the 'products' table, extract 'id', 'launched_on', 'price' and add 'prev_price', i.e. the 'price' of the product logically considered the 'previous' one, in ascending 'launched_on' order.

संपादक लोड हो रहा है...
संकेत दिखाएँ

Use LAG(price) OVER(ORDER BY launched_on ASC)

3 प्रयासों के बाद समाधान उपलब्ध है

व्यायाम#sql.m13.l4.e2
प्रयास: 0लोड हो रहा है...

How would you compute the rating jumps per individual user? Simulate it: from the 'reviews' table extract 'customer_id', 'created_at', 'rating' and 'next_rating' (the next review of the same customer over time). So partition by 'customer_id', order by 'created_at' and use the right window function to peek ahead.

संपादक लोड हो रहा है...
संकेत दिखाएँ

LEAD() together with PARTITION BY and ORDER BY in the OVER.

3 प्रयासों के बाद समाधान उपलब्ध है