执行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
的行和带有任何其他值的行才能显示。有可能这样做吗?
答案 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