我有表的集合在關係數據庫SQL - 計數與嵌套子查詢
products
categories
orders
line_items
customers
產品與類別具有多對多關係(連接表categories_products
),並且也具有並屬於許多orders
到line_items
,這是products
和orders
的連接表,帶有一個id。 A customer
也有很多orders
。
我試圖把一些SQL,這將使我這種反應:
customer_id | customer_first_name | category_id | category_name | number_purchased
-----------------------------------
1 |Jack | 1 | Electronics | 15
2 |Jill | 1 | Electronics | 2
2 |Jill | 2 | Hiking | 3
這是SQL的巨厚片我一直在試圖用它來獲取這些值:
SELECT
DISTINCT customers.id AS customer_id,
customers.first_name AS customer_first_name,
categories.id AS category_id,
categories.name AS category_name,
(
SELECT count(li.id) FROM line_items li
INNER JOIN orders o ON li.order_id = o.id
INNER JOIN products p ON li.product_id = p.id
INNER JOIN categories_products cp ON cp.product_id = p.id
WHERE
o.customer_id = customer_id
AND o.status = 3
AND cp.category_id = category_id
) AS number_purchased
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.id
LEFT JOIN line_items li ON li.order_id = orders.id
LEFT JOIN products ON products.id = li.product_id
LEFT JOIN categories_products catpr ON catpr.product_id = products.id
LEFT JOIN categories ON catpr.category_id = categories.id
只有計數本身是錯誤的。而不是獲取客戶在特定類別中購買的訂單項數量,而是對所有已完成訂單的LineItem進行計數。
如何才能讓計數正確地代表customer
在category
內購買的line_items
的數量?
注意:在SQL文本中,o.status = 3
正在使用枚舉來指示訂單是「完整的」。
你的查詢看起來像它特定於類別。將刪除'number_purchased'返回一個類似的輸出? –
我建議通過添加分組 –
@RudyM'number_purchased'是唯一返回不正確的值。理論上我可以在每個'customer'和'category'的每個組合或代碼級別的單獨查詢中獲得'number_purchased'值,但是我特別試圖編寫單個SQL語句來正確輸出所有這些信息 – PapaPoison