繁体   English   中英

SQL:语句仅返回第一行的小计

[英]SQL: Statement only returns subtotal of the first row

我有如下示例数据:
样本数据

我使用下面的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
; 

并实现了这一点:
结果

但这只是给我第一行的小计。

尝试这个:

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;

product_category_id在其他表中不存在。 因此,小计结果为NULL。

SUM(1 + NULL)== NULL。 您可以使用IF或COALESCE将NULL转换为0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM