日期:2014-05-17 浏览次数:20580 次
USE ProductWarehouseSecurity
GO
-->生成表a
if object_id('a') is not null
drop table a
Go
Create table a([qty] smallint,[year] smallint,[month] smallint)
Insert into a
Select 15,2013,1
-->生成表b
if object_id('b') is not null
drop table b
Go
Create table b([qty] smallint,[year] smallint,[month] smallint)
Insert into b
Select -3,2012,12
Union all Select 9,2012,11
Union all Select 1,2012,10
/*
现在有a表,数据为
qty year month
15 2013 1
b表,数据为
qty year month
-3 2012 12
9 2012 11
1 2012 10
现在想得到这样的数据
18 2012 12
9 2012 11
8 2012 10
8 2012 9
。。。
8 2012 1
*/
Go
----------------- 1.
;WITH t AS(
SELECT
b.year
,b.month
,a.qty-b.qty AS qty
FROM
(SELECT qty FROM a WHERE month=1 AND year=2013) AS a
,b
WHERE NOT EXISTS(SELECT 1 FROM b AS x
WHERE x.month>b.month
AND x.year=2012
)
UNION ALL
SELECT
b.year
,b.month
,t.qty-b.qty
FROM
b
,t
WHERE b.year=t.year
AND b.month=t.month-1
)
,t2 AS (
SELECT
ISNULL(t.qty,q.qty) AS qty
,b.year
,a.number AS month
FROM master.dbo.spt_values AS a
INNER JOIN (SELECT year,MAX(month) AS month FROM t GROUP BY year) AS b ON a.number<=b.month
LEFT JOIN t ON b.year=t.year AND a.number=t.month
INNER JOIN (SELECT year,qty FROM t WHERE NOT EXISTS(SELECT 1 FROM t AS x WHERE x.year=t.year AND x.month<t.month)) AS q ON b.year=q.year
WHERE a.number>0
AND a.type='P'
)SELECT * FROM t2
ORDER BY year DESC,month DESC
/*
qty year month
------ ------ -----------
18 2012 12
9 2012 11
8 2012 10
8 2012 9
8 2012&