假设我们要获得总销售额大于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