整理多个技术点的sql综合应用:(开拓思路,SELECT子句内嵌子查询)---续,用表变量替换临时表
Posted on 2010-01-26 09:09 召冠 阅读(499) 评论(0) 编辑 收藏 举报--设定起始日期为当前年的第一天
DECLARE @dtDate DATETIME, @iRow INT
SET @dtDate = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
SET @iRow = 10
--批量生成测试数据,日期规则递增的列、及随机的数值列
DECLARE @tmp TABLE( dtDate DATETIME, dcQty INT, dcTotalQty INT )
DECLARE @iRank INT
SET @iRank = 1
INSERT INTO @tmp ( dtDate, dcQty )
VALUES ( @dtDate, CHECKSUM(NEWID()) % 100 )
WHILE @iRank <= @iRow
BEGIN
INSERT INTO @tmp ( dtDate, dcQty )
SELECT DATEADD(DAY, @iRank, dtDate),
CHECKSUM(NEWID()) % 100
FROM @tmp
WHERE DATEADD(DAY, @iRank, dtDate) < DATEADD(DAY, @iRow, @dtDate)
SET @iRank = @iRank * 2
END
--显示日期列、当前数值、累计数值
SELECT a.dtDate,
a.dcQty,
( SELECT SUM(b.dcQty)
FROM @tmp AS b
WHERE b.dtDate <= a.dtDate
) AS dcTotalQty
FROM @tmp AS a