我有以下示例数据:
我使用下面的SQL语句:
select a.product_category_id, b.Favorite, c.In_Cart,d.Pre_sales_order,
sum(b.Favorite)+sum(c.In_Cart)+sum(d.Pre_sales_order) as SubTotal
from
(select distinct product_category_id
from item_activity
where last_item_status_code in (6,7,8)
) a
left join
(select product_category_id, count(last_item_status_code) as Favorite
from .item_activity
where last_item_status_code='6'
group by product_category_id
) b on a.product_category_id=b.product_category_id
left join
(select product_category_id, count(product_category_id) as In_Cart
from item_activity
where last_item_status_code='7'
group by product_category_id
) c on c.product_category_id=a.product_category_id
left join
(select product_category_id, count(product_category_id) as Pre_sales_order
from item_activity
where last_item_status_code='8'
group by product_category_id
) d on d.product_category_id=a.product_category_id
group by a.product_category_id
;
并实现了这一点:
但它只是给我第一行的小计......
答案 0 :(得分:1)
试试这个:
select product_category_id,
sum(case when last_item_status_code=6 then 1 else 0 end) As Favorite,
sum(case when last_item_status_code=7 then 1 else 0 end) As In_Cart,
sum(case when last_item_status_code=8 then 1 else 0 end) As Pre_sales_order,
count(last_item_status_code) as SubTotal
from item_activity
where last_item_status_code in (6,7,8)
group by product_category_id;
答案 1 :(得分:0)
product_category_id并不存在于其他表中。因此,小计结果为NULL。
SUM(1 + NULL)== NULL。您可以使用IF或COALESCE将NULL转换为0。