T1 - id, name, userID (stocks) - not really used in this cased
T2 - id, name, stockID, userID (categories)
T3 - id, name, stockID, categoryID, quality, userID (goods)


“质量”列可以是“ 0”(好)或“ 1”(差),每种商品(即使是同一种类)也= 1行

该SQL(我可以得到的这个“远”)仅显示好坏的总数,并且如果存在类别,但没有任何行,那么最终结果中不会显示它:

SELECT T2.name, COUNT(*) AS TOTAL FROM T3
LEFT JOIN T2 ON T2.id=T3.categoryID
WHERE T3.stockID=2 GROUP BY T3.categoryID


结果:

CATEGORY  - TOTAL
category1 - 1237
category2 -  857
category3 -  125


因为没有行,所以没有显示category4,但是我需要显示每一个行,即使T3行不存在,当然也包括坏的东西。

所需结果:

CATEGORY  - BAD / TOTAL
category1 - 425 / 1237
category2 - 326 /  857
category3 -   0 /  125
category4 -   0 /    0

最佳答案

SELECT T2.name, SUM(CASE WHEN T3.quality=1 THEN 1 ELSE 0 END)AS BAD,
       COUNT(*)AS TOTAL
FROM T2
LEFT JOIN T3 ON T2.id=T3.categoryID
WHERE t2.stockid=2
GROUP BY T2.name;

关于mysql - 将具有不同WHERE和GROUP BY的行计数为1结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21799485/

10-11 07:11