2013-05-05 19 views
5

ho questi due query come di seguito:sottraendo due colonne differenti da 2 selezioni sulla stessa tavola

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

questa query dà la somma delle quantità di elementi diversi in due tipi di date, date-created e data-.

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

questa query dà la somma di quantità prelevata dal magazzino di elementi diversi in data-out -s.

Voglio fare un DataSet che ha i seguenti campi:

globalid - nome - prezzo - in magazzino - venduto - totale

ho trovato alcuni esempi online, ma sono principalmente con la funzione count, o se con sum, solo una delle query ha una condizione, non entrambe. Sto usando SQL Server, ogni aiuto è apprezzato.

risposta

2

Sembra come è possibile utilizzare CASE con SUM - senza bisogno di alcun sottointerrogazioni:

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 
Problemi correlati