如果SUM返回某个值,有没有办法在SQL中显示一行?

时间:2017-01-29 17:19:00

标签: mysql sql

执行SUM查询时是否可以只显示某个值?例如,我有一个business_user表和一个慈善机构的campaigns表。

如您所见,业务用户2有2个有效广告系列,而商业用户1有0个有效广告系列。

mysql> select business_id, active from campaigns;
+-------------+--------+
| business_id | active |
+-------------+--------+
|           2 |      1 |
|           2 |      1 |
|           1 |      0 |
+-------------+--------+
3 rows in set (0.00 sec)

mysql> SELECT b.business_id, SUM(CASE WHEN c.active = true THEN 1 ELSE 0 END) as active_campaigns
    -> FROM business_users b, campaigns c
    -> WHERE b.business_id = c.business_id
    -> GROUP BY c.business_id;
+-------------+------------------+
| business_id | active_campaigns |
+-------------+------------------+
|           1 |                0 |
|           2 |                2 |
+-------------+------------------+

每当我执行上面的查询时,我希望显示带有active_campaigns = 0的行和带有任何其他值的行才能显示。有可能这样做吗?

2 个答案:

答案 0 :(得分:2)

HAVING active_campaigns = 0添加到查询的末尾

答案 1 :(得分:1)

SELECT b.business_id, SUM(CASE WHEN c.active = true THEN 1 ELSE 0 END) as active_campaigns
FROM business_users b, campaigns c
WHERE b.business_id = c.business_id
GROUP BY c.business_id
Having SUM(CASE WHEN c.active = true THEN 1 ELSE 0 END) = 0