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 婆婆高寿祝福语大全简短