我有以下两个查询:
SELECT globalid, name, price, sum(qnt) as pozitive
from main
where [date-out] is null
group by globalid, name, price;
此查询提供两种日期中不同项目的数量总和,日期创建和日期 - 。
SELECT globalid, sum(qnt) as negative
from main
where [date-out] is not null
group by globalid;
此查询提供 date-out -s中不同商品的存储量。
我想创建一个包含以下字段的DataSet:
globalid - 名称 - 价格 - 库存 - 已售出 - 总
我在网上找到了一些例子但是,它们主要是使用count函数,或者如果使用sum,只有一个查询有条件,而不是两者。我正在使用SQL Server,感谢任何帮助。
答案 0 :(得分: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
答案 1 :(得分: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