2013-05-05 43 views
5

從其減去兩個不同的列從2個選擇我有這兩個查詢如下:在同一個表

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 - - 價格 - 股票 - 出售 -

我有在網上找到了一些例子,但是,它們主要與計數函數有關,或者如果總和,只有一個查詢有一個條件,而不是兩個。我正在使用SQL Server,任何幫助表示讚賞。

回答

2

好像你可以使用CASESUM - 不需要任何的子查詢:

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