SELECT username, balance, ROW_NUMBER() OVER (ORDER BY balance DESC) AS rank FROM users;
SELECT u.username, o.total, ROUND(AVG(o.total) OVER (PARTITION BY o.user_id), 2) AS user_avg FROM orders o JOIN users u ON u.id = o.user_id ORDER BY u.username, o.created_at;
SELECT name, price, DENSE_RANK() OVER (ORDER BY price DESC) AS drnk FROM products;
SELECT category, product, price FROM ( SELECT c.name AS category, p.name AS product, p.price, ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY p.price DESC) AS rn FROM products p JOIN categories c ON c.id = p.category_id ) t WHERE rn = 1;
SELECT u.username, o.created_at::date, o.total, LAG(o.total) OVER (PARTITION BY o.user_id ORDER BY o.created_at) AS prev_total, o.total - LAG(o.total) OVER (PARTITION BY o.user_id ORDER BY o.created_at) AS diff FROM orders o JOIN users u ON u.id = o.user_id ORDER BY u.username, o.created_at;
SELECT id, created_at::date, total, SUM(total) OVER (ORDER BY created_at) AS running_total FROM orders WHERE status = 'done' ORDER BY created_at;
SELECT c.name AS category, p.name, p.price, ROUND(PERCENT_RANK() OVER (PARTITION BY c.id ORDER BY p.price)::numeric, 2) AS pct_rank FROM products p JOIN categories c ON c.id = p.category_id ORDER BY category, pct_rank;
SELECT u.username, o.created_at::date, o.total, ROUND(AVG(o.total) OVER ( PARTITION BY o.user_id ORDER BY o.created_at ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ), 2) AS moving_avg_3 FROM orders o JOIN users u ON u.id = o.user_id ORDER BY u.username, o.created_at;
WITH user_spending AS ( SELECT user_id, SUM(total) AS total_spent FROM orders WHERE status = 'done' GROUP BY user_id ), ranked AS ( SELECT u.username, us.total_spent, SUM(us.total_spent) OVER (ORDER BY us.total_spent DESC) AS cum_spent, SUM(us.total_spent) OVER () AS grand_total FROM user_spending us JOIN users u ON u.id = us.user_id ) SELECT username, total_spent, ROUND(cum_spent / grand_total * 100, 1) AS cum_pct FROM ranked WHERE cum_spent <= grand_total * 0.5 OR total_spent = (SELECT MAX(total_spent) FROM user_spending) ORDER BY total_spent DESC;
|