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;
7 條件聚合
條件聚合是指根據指定條件應用條件聚合函數。例如,如果想計算老客戶訂單的平均銷售額:
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)可讓分析師根據與源表的連接結果在目標表中插入、更新或刪除記錄。比如,要同步兩個包含客戶數據的表。
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);
10 情況語句
情況語句支持在SQL查詢中應用條件邏輯。例如,使用情況語句根據客戶的總購買金額對其進行分類。
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;