SQL 重构查询以使用通用表表达式
示例
假设我们要获得总销售额大于20的所有产品类别。
这是一个没有公用表表达式的查询:
SELECT category.description, sum(product.price) as total_sales FROM sale LEFT JOIN product onsale.product_id= product.id LEFT JOIN category onproduct.category_id= category.id GROUP BY category.id, category.description HAVING sum(product.price) > 20
以及使用通用表表达式的等效查询:
WITH all_sales AS ( SELECT product.price,category.idas category_id,category.descriptionas category_description FROM sale LEFT JOIN product onsale.product_id= product.id LEFT JOIN category onproduct.category_id= category.id ) , sales_by_category AS ( SELECT category_description, sum(price) as total_sales FROM all_sales GROUP BY category_id, category_description ) SELECT * from sales_by_category WHERE total_sales > 20
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短