项目和类别(1:N)如何在单个SQL查询中获取每个类别的总活动项目数和总活动项数?

时间:2011-04-21 08:30:41

标签: mysql sql

item_id
title
active = 1/0

items_categories_map

item_id
category_id

我需要得到结果

category_id
items_total (any value of items.active)
items_active (items.active = 1)
items_inactive (items.active = 0)

是否可以在不使用UNION的情况下在单个SQL查询中获得此类结果?

谢谢!

2 个答案:

答案 0 :(得分:1)

使用以下模板......

COUNT(items.active) AS items_total,
SUM(items.active)   AS items_active,
SUM(1-items.active) AS items_inactive


或者当您的值不是1或0时......

SUM(CASE WHEN items.active = 0 THEN 1 ELSE 0 END) as items_inactive

答案 1 :(得分:1)

要添加到Dems:如果您想按进行分组,还要使用总计:

select items.id
 , COUNT(items.active) AS items_total
 , SUM(ifnull(items.active,0)) AS items_active
 , SUM(1-ifnull(items.active,0)) AS items_inactive
FROM items
GROUP BY items.somefield WITH ROLLUP

+------+-------------+---------------+----------------+
| id   | items_total | items_active  | items_inactive |
+------+-------------+---------------+----------------+
| 1    | 2           | 1             | 1              |
| 2    | ....
| null |100          | 60            | 40             |<<- grand total
+------+-------------+---------------+----------------+

with rollup你会在底部获得一个总排。

ifnull需要吗?
如果items.active可以为null,那么你需要ifnull()来防止总和被评估为null并弄乱你的结果。