请教SQL语句,查询每月数据,但其中有几个月的没有,要取前月的数据。

glvicky 2013-02-05 02:06:26
ID Number Price Year Month
1 1 123.00 2013 2
2 1 182.00 2013 1
3 1 141.00 2012 12
4 1 162.00 2012 7
5 1 160.00 2012 1

数据格式如上,要查询Number为1的产品的最近1年的价格,如果某月为空,则取前面有价格的月份,如查询时间2013年1月,编号为1的产品最一年的价格结果应为如下:
Number Pirce Year Month
1 182.00 2013 1
1 141.00 2012 12
1 162.00 2012 11
1 162.00 2012 10
1 162.00 2012 9
1 162.00 2012 8
1 162.00 2012 7
1 160.00 2012 6
...
1 160.00 2012 2

请问存储过程应该如何实现?
...全文
809 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
glvicky 2013-02-05
  • 打赏
  • 举报
回复
非常感谢~··
我腫了 2013-02-05
  • 打赏
  • 举报
回复
USE test
GO

-->生成表tb

if object_id('tb') is not null 
	drop table tb
Go
Create table tb([ID] smallint,[Number] smallint,[Price] numeric(5,2),[Year] smallint,[Month] smallint)
Insert into tb
Select 1,1,123.00,'2013',2
Union all Select 2,1,182.00,'2013',1
Union all Select 3,1,141.00,'2012',12
Union all Select 4,1,162.00,'2012',7
Union all Select 5,1,160.00,'2012',1
Go

DECLARE 
	@Number SMALLINT
	,@Date DATETIME

SET @Number=1



SET @Date=GETDATE()

;WITH t AS (
	SELECT 
			DATEADD(mm,1,LTRIM(a.Year)+RIGHT(100+b.number,2)+'01') AS Date
			,a.Year
			,b.number AS Month
		FROM 
			(
				SELECT 
						Year
						,MIN(Month) AS mix_Month
						,MAX(Month) AS max_Month 
					FROM tb 
					WHERE Number=@Number 
					GROUP BY Year
			) AS a
			,master.dbo.spt_values AS b
		WHERE b.number BETWEEN a.mix_Month AND a.max_Month
			AND b.type='P'
),t2 AS (
	select 
			@Number AS Number
			,a.Price
			,t.Year
			,t.Month
			,t.Date
		from 
			(
				SELECT 
						Number
						,Price
						,Year
						,Month
						,DATEADD(mm,1,LTRIM(Year)+RIGHT(100+Month,2)+'01') AS Date 
					FROM tb 
					WHERE Number=@Number
			) AS a
			RIGHT JOIN t ON a.Date=t.Date
)
SELECT 
		a.Number
		,ISNULL(a.Price,b.Price) AS Price
		,a.Year
		,a.Month
	FROM t2 AS a
		OUTER APPLY(SELECT Price
						FROM t2 AS x
						WHERE x.Date=(SELECT MAX(Date) FROM t2 AS o WHERE o.Date<a.Date AND o.Price IS NOT NULL)
				) AS b
	WHERE a.Date<=@Date AND a.Date>=DATEADD(yy,-1,@date)
	ORDER BY a.Date DESC
	
/*
Number Price   Year   Month
------ ------- ------ -----------
1      182.00  2013   1
1      141.00  2012   12
1      162.00  2012   11
1      162.00  2012   10
1      162.00  2012   9
1      162.00  2012   8
1      162.00  2012   7
1      160.00  2012   6
1      160.00  2012   5
1      160.00  2012   4
1      160.00  2012   3
1      160.00  2012   2
*/

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧