WITHRECURSIVE subordinates AS ( SELECT employee_id, name, manager_id FROM employees WHERE manager_id = 'manager_id_of_interest' UNIONALL SELECT e.employee_id, e.name, e.manager_id FROM employees e JOIN subordinates s ON e.manager_id = s.employee_id ) SELECT * FROM subordinates;
SELECT product, month, sales FROM ( SELECT'Jan'ASmonth, product, sales_jan AS sales FROM sales_data UNIONALL SELECT'Feb'ASmonth, product, sales_feb AS sales FROM sales_data UNIONALL SELECT'Mar'ASmonth, product, sales_mar AS sales FROM sales_data ) AS unpivoted_sales;
SELECT customer_id, AVG(CASEWHEN order_count > 1THEN order_total ELSENULLEND) AS avg_sales_repeat_customers FROM ( SELECT customer_id, COUNT(*) AS order_count, SUM(order_total) AS order_total FROM orders GROUPBY customer_id ) AS customer_orders;
SELECT DATE_TRUNC('month', order_date) ASmonth, SUM(sales_amount) AS total_sales FROM sales GROUPBY DATE_TRUNC('month', order_date);
9 合并語句
合并語句(也稱為 UPSERT 或 ON DUPLICATE KEY UPDATE)可讓分析師根據(jù)與源表的連接結(jié)果在目標(biāo)表中插入、更新或刪除記錄。比如,要同步兩個(gè)包含客戶數(shù)據(jù)的表。
MERGEINTO target_table AS t USING source_table AS s ON t.customer_id = s.customer_id WHENMATCHEDTHEN UPDATESET t.name = s.name, t.email = s.email WHENNOTMATCHEDTHEN INSERT (customer_id, name, email) VALUES (s.customer_id, s.name, s.email);
SELECT customer_id, CASE WHEN total_purchase_amount >= 1000THEN'Platinum' WHEN total_purchase_amount >= 500THEN'Gold' ELSE'Silver' ENDAS customer_category FROM ( SELECT customer_id, SUM(order_total) AS total_purchase_amount FROM orders GROUPBY customer_id ) AS customer_purchases;