27,579
社区成员
发帖
与我相关
我的任务
分享
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([仓位] nvarchar(22),[数量] int,[时间] Date)
Insert #T
select N'W1',20,'2017/1/2' union all
select N'W1',-10,'2017/2/2' union all
select N'W2',5,'2017/1/4' union all
select N'W3',8,'2017/3/4' union all
select N'W2',9,'2017/2/4' union all
select N'W1',-6,'2017/4/5'
Go
--测试数据结束
;WITH tempa AS (
SELECT 仓位 ,
convert(varchar(7),时间,23) AS 时间 ,
SUM(数量) AS 数量
FROM #T
GROUP BY 仓位 ,
时间
)
SELECT b.仓位 ,
b.数量 ,
b.时间 AS 年月 ,
ISNULL(SUM(a.数量), 0) AS 期初
FROM tempa b
LEFT JOIN tempa a ON a.仓位 = b.仓位
AND CONVERT(DATETIME, b.时间 + '-01') > CONVERT(DATETIME, a.时间
+ '-01')
GROUP BY b.仓位 ,
b.数量 ,
b.时间
ORDER BY b.仓位 ,
b.时间;
select 仓位=LocCode,
年月=convert(varchar(7),[Time],23),
进出求和=sum(number)
from [表名]
group by LocCode,convert(varchar(7),[Time],23)