具有通用表表达式的复杂SQL的示例
示例
假设我们要从“热门类别”中查询“最便宜的产品”。
这是使用公用表表达式的查询示例
-- all_sales: just a simple SELECT with all the needed JOINS WITH all_sales AS ( SELECT product.priceas 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 ) -- Group by category , sales_by_category AS ( SELECT category_id, category_description, sum(product_price) as total_sales FROM all_sales GROUP BY category_id, category_description ) -- Filtering total_sales > 20 , top_categories AS ( SELECT * from sales_by_category WHERE total_sales > 20 ) -- all_products: just a simple SELECT with all the needed JOINS , all_products AS ( SELECT product.idas product_id, product.descriptionas product_description, product.priceas product_price, category.idas category_id, category.descriptionas category_description FROM product LEFT JOIN category onproduct.category_id= category.id ) -- Order by product price , cheapest_products AS ( SELECT * from all_products ORDER by product_price ASC ) -- Simple inner join , cheapest_products_from_top_categories AS ( SELECT product_description, product_price FROM cheapest_products INNER JOIN top_categories ON cheapest_products.category_id = top_categories.category_id ) --The main SELECT SELECT * from cheapest_products_from_top_categories