TGViewer
SQL Programming Resources SQL Programming Resources @sqlanalyst · 76.7K subscribers
Post #2785 1.32K
SELECT
customer_id,
order_date,
amount,

SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS running_total

FROM orders;


Practice 5

Assign a unique order number to each customer's orders.

SELECT
customer_id,
order_id,
order_date,

ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date
) AS order_number

FROM orders;


🧪 Mini SQL Challenge

You have:

sales

sale_id

customer_id

sale_date

amount

Write a query that returns:

• Customer ID

• Sale date

• Amount

• Previous sale amount

• Difference from previous sale

• Running customer spending

• Customer's transaction number

Solution

SELECT
customer_id,
sale_date,
amount,

LAG(amount) OVER (
PARTITION BY customer_id
ORDER BY sale_date
) AS previous_amount,

amount - LAG(amount) OVER (
PARTITION BY customer_id
ORDER BY sale_date
) AS difference_from_previous,

SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
) AS running_spending,

ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY sale_date
) AS transaction_number

FROM sales;


What did we use?

LAG()

→ Previous transaction

SUM() OVER()

→ Running spending

ROW_NUMBER()

→ Transaction sequence

PARTITION BY

→ Separate calculations for each customer

ORDER BY

→ Establish chronological order

💡 Double Tap ❤️ For More
  • ❤ 5
  • 👏 1
More from @sqlanalyst
  1. Oct 7, 2026🚀𝗣𝗮𝘆 𝗔𝗳𝘁𝗲𝗿 𝗣𝗹𝗮𝗰𝗲𝗺𝗲𝗻𝘁 𝗧𝗿𝗮𝗶𝗻𝗶𝗻𝗴 | 𝗕𝗲𝗰𝗼𝗺𝗲 𝗮 𝗙𝘂𝗹𝗹𝘀𝘁𝗮𝗰…
  2. Oct 7, 2026SQL Interview Series — Part 4 📌 Question 4: Find the Highest Salary in Each Department Su…
  3. Oct 7, 2026𝗠𝗮𝘀𝘁𝗲𝗿 𝗣𝗼𝘄𝗲𝗿 𝗕𝗜 𝗳𝗼𝗿 𝗙𝗥𝗘𝗘! 🔥 Learn Power BI through these FREE learnin…
  4. Sep 29, 2026SQL Interview Series — Part 2 📌 Question 2: Find Duplicate Records Suppose you have an Em…
  5. Sep 29, 2026𝗙𝗥𝗘𝗘 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲𝘀 𝗧𝗼 𝗟𝗲𝗮𝗿𝗻 𝗔𝗜 𝗶𝗻 𝟮𝟬𝟮𝟲🚀 ​ Explore 6 free resource…
  6. Sep 29, 2026SQL Interview Series — Part 1 Hi guys, let's start a SQL interview series covering frequen…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →