2017-05-19 36 views
0

我有樣本數據如下圖所示:
Sample DataSQL:語句只返回第一行的小計

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

,取得了這一點:
result

但它只是給我第一行的小計......

+0

好的,現在我們可以真正閱讀您的問題,我們終於可以開始幫助您。只有5分鐘的時間,所以你只錯過了你潛在的頭版觀衆的一半。將來,請記住,在發佈之前對該問題做出更多努力將會對可能提供幫助的人數產生巨大影響。 –

+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; 
+0

謝謝喬爾,問題解決〜 – SSiu

0

product_category_id在其他表中不存在。所以小計導致NULL。

SUM(1 + NULL)== NULL。您可以使用IF或COALESCE將NULL轉換爲0.

+0

謝謝dmb,我也會嘗試你的建議.. – SSiu