我想创建一个选择类别名称并计算每个类别中广告(有效)的最大值的查询,我已经这样做了:
SELECT
cat.cat_id,
cat.cat_desc,
COUNT(ad_id) AS cat_total_ads
FROM
tab_categories AS cat LEFT JOIN
tab_ads AS ads ON ads.cat_id = cat.cat_id
WHERE
cat_active = @cat_active AND
cat_deleted = @cat_deleted
GROUP BY
cat_desc, cat.cat_id
此查询也在计算非活动广告。如何为非活动广告设置值0?
答案 0 :(得分:3)
答案 1 :(得分:1)
SUM(CASE .....然后其他0结束)作为colName应该为你做!!
尝试这个我没有表重新进行测试,但这或类似的东西应该有用。
select
cat.cat_id,
cat.cat_desc,
count(ad_id) as Total,
sum(case when ad_id= 0 then 1 else 0 end) as 'ad_id'
from
tab_categoriesAS cat LEFT JOIN
tab_ads AS ads ON ads.cat_id = cat.cat_id
WHERE
cat_active = @cat_active AND
cat_deleted = @cat_deleted
GROUP BY
cat_desc, cat.cat_id