[英]count amount of transactions per type per ID in mysql
擁有三張桌子
用戶
ID email
1 ..
2 ..
3 ..
4 ..
交易量
userID transactionID productID
1 1111 999
1 1112 897
2 1222 989
3 1333 989
4 1444 897
4 1114 897
產品展示
productID type
999 Sports
989 Fashion
789 Fashion
897 Sports
想要創建一個表,我可以在其中找到每個 UserID 的類型總數。 所以最終我想創建以下內容
UserID Sports Fashion
1 1 1
2 0 1
3 0 1
4 2 0
嘗試使用以下代碼
SELECT u.email,
p.productID,
COUNT(CASE WHEN type = 'Sports' THEN 1 ELSE 0 END),
COUNT(CASE WHEN type = 'Fashion' THEN 1 ELSE 0 END)
from transactions t
LEFT JOIN users u ON u.ID = t.userID
LEFT JOIN products p ON t.productID = p.productID
group by u.email
因此它沒有像希望的那樣工作。
您可以加入並進行條件聚合:
select
u.id,
sum(p.type = 'Sports') sports,
sum(p.type = 'Fashion') fashion
from users u
inner join transactions t on t.userid = u.id
inner join products p on p.id = t.productid
group by u.id
原始查詢的問題是使用count()
:這個聚合 function 考慮了所有非空值:所以1
和0
都被計算在內。所以你可以使用sum()
(如上所示),或更改case
表達式以在不匹配時返回null
,如下所示:
COUNT(CASE WHEN type = 'Sports' THEN 1 END),
COUNT(CASE WHEN type = 'Fashion' THEN 1 END)
旁注:大概,您想要inner join
而不是left join
。 看起來您的數據沒有孤立記錄 - inner join
比left join
更有效。
id | sports | fashion -: | -----: | ------: 1 | 2 | 0 2 | 0 | 1 3 | 0 | 1 4 | 2 | 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.