SELECT TOP (100) PERCENT yy, mm, Item, SUM(Qty) AS qty, COALESCE
((SELECT SUM(Qty) AS Expr1
FROM dbo.v_Storage AS p
WHERE (Item = i.Item) AND (mm < i.mm) AND (yy = i.yy)), 0) AS OpnQty
FROM dbo.v_Storage AS i
GROUP BY yy, mm, Item
ORDER BY yy, mm, Item
它带来了这个:
但缺少带突出显示的项目,因为mm = 3时qty为零。任何帮助将不胜感激。
答案 0 :(得分:1)
如果您需要年,月和项目的所有组合,则需要生成这些组合,然后引入数据。其余的以类似的方式完成:
select yy.yy, mm.mm, i.Item,
sum(s.qty) as qty,
ifnull((SELECT SUM(Qty)
FROM dbo.v_Storage s2
WHERE (s2.Item = i.Item) AND (s2.mm < mm.mm) AND (s2.yy = yy.yy)
), 0) AS OpnQty
from (select distinct yy from v_Storage) yy cross join
(select distinct mm from v_Storage) mm cross join
(select distinct item from v_Storage) i left outer join
v_Storage s
on s.yy = yy.yy and s.mm = mm.mm and s.item = i.item
group by yy.yy, mm.mm, i.item
order by yy.yy, mm.mm, i.item;
请注意,我将coalesce()
替换为ifnull()
。在这种情况下,ifnull()
会更快,因为coalesce()
将执行两次子查询。
如果您使用的是SQL Server 2012,则可以使用累积总和替换整个子查询:
select yy.yy, mm.mm, i.Item,
sum(s.qty) as qty,
coalesce(sum(s.qty), 0) over (partition by i.item, yy.yy order by mm.mm) as OpnQty
from (select distinct yy from v_Storage) yy cross join
(select distinct mm from v_Storage) mm cross join
(select distinct item from v_Storage) i left outer join
v_Storage s
on s.yy = yy.yy and s.mm = mm.mm and s.item = i.item
group by yy.yy, mm.mm, i.item
order by yy.yy, mm.mm, i.item;