2013-05-05 6 views
5

以下のように私はこれらの2つのクエリがあります。このクエリは、日付の2種類、日に作成したでさまざまなアイテムの数量の合計を与え、同じテーブルの上に2つの選択から二つの異なるカラムをSubstracting

SELECT globalid, name, price, sum(qnt) as pozitive 
from main 
where [date-out] is null 
group by globalid, name, price; 

date-in

SELECT globalid, sum(qnt) as negative 
from main 
where [date-out] is not null 
group by globalid; 

このクエリは日付アウト -sでさまざまなアイテムの収納から取り出した量の合計を提供します。

私は、次のフィールドを持っているデータセットを作りたい:

globalid - - 価格 - 在庫 - 私が持っている

- を販売オンラインでいくつかの例を見つけましたが、主にcount関数を使用していました。また、sumを使用すると、クエリの1つだけに条件があり、両方ではありません。私はSQL Serverを使用している、任意の助けに感謝します。

答えて

2

あなたはSUMCASEを使用することはできませんように思える - すべてのサブクエリの必要性:

SELECT 
    globalid, 
    name, 
    price, 
    sum(case when [date-out] is null then qnt end) positive, 
    sum(case when [date-out] is not null then qnt end) negative, 
    sum(qnt) total 
from main 
group by 
    globalid, 
    name, 
    price 
1
select x.globalid, x.name, x.price, x.positive as [in stock], x.negative as [sold], x.positive + x.negative as [total] 
from 
(
SELECT globalid, 
      name, 
      price, 
    sum(case when [date-out] is not null then qnt else 0 end) as negative, 
    sum(case when [date-out] is null then qnt else 0 end) as positive 
from main 
where [date-out] is not null 
group by globalid, name, price 
) as x 
関連する問題