TGViewer
SQL Programming Resources SQL Programming Resources @sqlanalyst · 76.7K subscribers
Post #2779 1.61K
Practice 4 — Rank customers by total spending.

WITH customer_sales AS (
SELECT customer_id, SUM(amount) AS total_spending
FROM orders GROUP BY customer_id
)
SELECT customer_id, total_spending,
RANK() OVER ( ORDER BY total_spending DESC ) AS spending_rank
FROM customer_sales;


Practice 5 — Create customer segments based on spending.

WITH customer_sales AS (
SELECT customer_id, SUM(amount) AS total_spending
FROM orders GROUP BY customer_id
)
SELECT customer_id, total_spending,
CASE WHEN total_spending >= 100000 THEN 'VIP'
WHEN total_spending >= 50000 THEN 'Premium'
ELSE 'Standard' END AS segment
FROM customer_sales;


🧪 Mini SQL Challenge

You have: orders(order_id, customer_id, amount, order_date)

Find the top 5 customers by total spending, but only consider customers who have placed at least 3 orders.

Solution:

WITH customer_metrics AS (
SELECT customer_id, COUNT(*) AS order_count, SUM(amount) AS total_spending
FROM orders GROUP BY customer_id
),
qualified_customers AS (
SELECT customer_id, order_count, total_spending
FROM customer_metrics WHERE order_count >= 3
)

SELECT customer_id, order_count, total_spending
FROM qualified_customers ORDER BY total_spending DESC LIMIT 5;


Logic:

Orders ↓

GROUP BY customer ↓

Calculate order count + spending ↓

Keep customers with ≥ 3 orders ↓

Sort by spending ↓

Return top 5

💡 Double Tap ❤️ For More
  • ❤ 8
More from @sqlanalyst
  1. Oct 7, 2026SQL Interview Series — Part 4 📌 Question 4: Find the Highest Salary in Each Department Su…
  2. Oct 7, 2026𝗠𝗮𝘀𝘁𝗲𝗿 𝗣𝗼𝘄𝗲𝗿 𝗕𝗜 𝗳𝗼𝗿 𝗙𝗥𝗘𝗘! 🔥 Learn Power BI through these FREE learnin…
  3. Sep 29, 2026SQL Interview Series — Part 2 📌 Question 2: Find Duplicate Records Suppose you have an Em…
  4. Sep 29, 2026𝗙𝗥𝗘𝗘 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲𝘀 𝗧𝗼 𝗟𝗲𝗮𝗿𝗻 𝗔𝗜 𝗶𝗻 𝟮𝟬𝟮𝟲🚀 ​ Explore 6 free resource…
  5. Sep 29, 2026SQL Interview Series — Part 1 Hi guys, let's start a SQL interview series covering frequen…
  6. Sep 28, 2026🧠 Real-World SQL Scenario-Based Questions & Answers 1. Get the 2nd highest salary from th…
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 →