关于查询一个递增累计值的断点问题

xumolly 2012-09-10 09:20:22
id name date value
129069 本期累计 201207 30
129069 本期累计 201206 29
129069 本期累计 201205 27
129069 本期累计 201204 35
129069 本期累计 201202 26
129069 本期累计 201201 24
129069 本期累计 201111 50
129069 本期累计 201110 30
129069 本期累计 201109 25
129069 本期累计 201107 24
129069 本期累计 201106 25
129069 本期累计 201006 30
129069 本期累计 201005 15
129069 本期累计 201004 13
求教大手,按照年份2012,2011,2010的不同,累计值按月份的增加应该是递增的,如何查询出错误的数据即递增数据中的断点?
即返回
id name date value
129069 本期累计 201204 35
129069 本期累计 201106 25
建表语句如下:
create table #test(id int,name varchar(9),date int,value int)
insert #test
select 129069,'本期累计',201207,30 union all
select 129069,'本期累计',201206,29 union all
select 129069,'本期累计',201205,27 union all
select 129069,'本期累计',201204,35 union all
select 129069,'本期累计',201202,26 union all
select 129069,'本期累计',201201,24 union all
select 129069,'本期累计',201111,50 union all
select 129069,'本期累计',201110,30 union all
select 129069,'本期累计',201109,25 union all
select 129069,'本期累计',201107,24 union all
select 129069,'本期累计',201106,25 union all
select 129069,'本期累计',201006,30 union all
select 129069,'本期累计',201005,15 union all
select 129069,'本期累计',201004,13
go
...全文
79 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
coleling 2012-09-10
  • 打赏
  • 举报
回复

create table #test(id int,name varchar(9),date int,value int)
insert #test
select 129069,'本期累计',201207,30 union all
select 129069,'本期累计',201206,29 union all
select 129069,'本期累计',201205,27 union all
select 129069,'本期累计',201204,35 union all
select 129069,'本期累计',201202,26 union all
select 129069,'本期累计',201201,24 union all
select 129069,'本期累计',201111,50 union all
select 129069,'本期累计',201110,30 union all
select 129069,'本期累计',201109,25 union all
select 129069,'本期累计',201107,24 union all
select 129069,'本期累计',201106,25 union all
select 129069,'本期累计',201006,30 union all
select 129069,'本期累计',201005,15 union all
select 129069,'本期累计',201004,13
go

--方法1
;WITH t AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY LEFT([date],4) ORDER BY [date]) AS GroupID
,LEFT([date],4) AS YY
,*
FROM #test
)
SELECT o.id,o.name,o.date,o.value
FROM t o
WHERE exists(SELECT * FROM t i WHERE i.YY = o.YY and i.GroupID-1 = o.GroupID and i.value < o.value)

--方法2
;WITH t AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY LEFT([date],4) ORDER BY [date]) AS GroupID
,LEFT([date],4) AS YY
,*
FROM #test
)
SELECT a.id,a.name,a.date,a.value
FROM t a left join t b ON a.YY = b.YY and a.GroupID = b.GroupID-1 and a.value > b.value
WHERE b.id is not null

/*
id name date value
----------- --------- ----------- -----------
129069 本期累计 201106 25
129069 本期累计 201204 35

(2 row(s) affected)
*/
xumolly 2012-09-10
  • 打赏
  • 举报
回复
补充下,月份有缺失的情况

34,588

社区成员

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

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