使用JOIN和GROUP的SQLite SELECT?

时间:2012-12-02 15:54:26

标签: sql sqlite

我正在尝试根据以下字符串的结果添加一列:

SELECT product_code AS "Product Code", SUM(quantity) AS "Quantity" 
FROM receipts_items
GROUP BY product_code
ORDER BY SUM(quantity) DESC

此字符串为我提供了产品代码和销售数量。根据产品代码,我需要添加的是产品代码的描述。

product_code和description列在同一个表中“产品” 数量在另一个表“receipts_items”

感谢!!!

1 个答案:

答案 0 :(得分:3)

您希望JOIN product_code上的两个表格LEFT JOIN

您确实应该使用CASE来捕获没有关联收据项的产品,然后在SUM中添加NULL语句,将SELECT p.product_code AS "Product Code", p.description AS "Description", SUM(CASE WHEN ri.quantity IS NULL THEN 0 ELSE ri.quantity END) AS "Quantity" FROM products AS p LEFT JOIN receipts_items AS ri ON ri.product_code = p.product_code GROUP BY p.product_code ORDER BY SUM(ri.quantity) DESC 值减少为0。

{{1}}