2013-05-05 12 views
5

mam te dwa pytania, jak poniżej:odjęcie dwóch różnych kolumn z 2 pozycje na tej samej tabeli

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

ta kwerenda daje sumę ilości różnych elementów w dwóch rodzajach dat data utworzone i data w.

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

ta kwerenda daje sumę ilości pobranych z przechowywania różnych przedmiotów w data-out -s.

Chcę, aby DataSet, który ma następujące pola:

globalid - nazwa - cenę - w magazynie - sprzedawany - całkowity

mam znaleźć kilka przykładów w Internecie, ale są one głównie z funkcją liczenia, lub jeśli z sumą, tylko jedno z zapytań ma warunek, a nie oba. Używam programu SQL Server, każda pomoc jest doceniana.

Odpowiedz

2

Wydaje się, można użyć CASE z SUM - nie potrzeba żadnych podzapytań:

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 
Powiązane problemy