2017-05-19 8 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分で、潜在的なフロントページの視聴者の約1/2を逃しただけです。将来的には、あなたが投稿する前に質問へのより多くの努力が、助けることができるかもしれない人々の数に大きな違いをもたらすことを忘れないでください。 –

+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

ありがとうJoel、問題解決〜 – SSiu

0

product_category_idは、他のテーブルに存在しません。したがって、小計はNULLになります。

SUM(1 + NULL)== NULL。 IFまたはCOALESCEを使用してNULLを0に変換することができます。

+0

ありがとうdmb、私もあなたの提案をお試しください.. – SSiu

関連する問題