5

我有以下两个查询:

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

此查询给出两种日期类型中不同项目的数量总和,即date-createddate-in

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

此查询给出了从date-out -s中不同项目的存储中取出的数量总和。

我想制作一个具有以下字段的数据集:

globalid -名称-价格-库存-已售出-总计

我在网上找到了一些示例,但它们主要是使用 count 函数,或者如果使用 sum,则只有一个查询有条件,而不是两者都有。我正在使用 SQL Server,不胜感激。

4

2 回答 2

2

似乎您可以使用CASE--SUM不需要任何子查询:

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
于 2013-05-05T16:13:21.507 回答
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
于 2013-05-05T16:12:13.500 回答