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;