SQL:选择上次更改列值的行

时间:2018-06-21 19:43:27

标签: sql sql-server

我需要获取更改数字的最新日期,我有此SQL语句

Select  
    a.group, a.date a.number 
From 
    xx.dbo.list a
Where 
    a.group in ('10, '10NC', '210')
    And a.date >= '2018-06-01'
    And a.number > 0
    And a. number <> (Select Top 1 b.number
                      From  xxx.dbo.list b
                      Where b.group  = a.group
                        And b.date >= '2018-06-01'
                        And b.number > 0
                        And b.date < a.date
                      Order by b.date desc)
order by a.date desc

我有一张看起来像这样的桌子

Group   date        Number  
--------------------------
10      2018-02-06  4
10      2018-04-06  4
10      2018-06-12  4
10NC    2018-02-06  68
10NC    2018-04-06  35
10NC    2018-06-11  35
10NC    2018-06-12  68
10NC    2018-06-13  35
210     2018-06-02  94
210     2018-06-04  100
210     2018-06-06  100
210     2018-06-07  93

我现在得到此输出,但是我只想获取带有X的行

Group   date        Number
------------------------------
10NC    2018-06-12  68  
10NC    2018-06-13  35   X
210     2018-06-04  100  
210     2018-06-07  93   X

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

您将使用lag()

select a.*
from (select  a.group, a.date,  a.number, lag(a.number) over (partition by group order by date) as prev_number
      From xx.dbo.list a
      where a.group in ('10', '10NC', '210') And
            a.date >= '2018-06-01' And
            a.number > 0
    ) a
where prev_number <> number;

答案 1 :(得分:0)

这是预期的吗?

DECLARE @List TABLE ([Group] VARCHAR(100), [Date]  DATE, Number INT)

INSERT INTO @List  
SELECT '10','2018-02-06',4
UNION ALL
SELECT '10','2018-04-06',4
UNION ALL
SELECT '10','2018-06-12',4
UNION ALL
SELECT '10NC','2018-02-06',68
UNION ALL
SELECT '10NC','2018-04-06',35
UNION ALL
SELECT '10NC','2018-06-11',35
UNION ALL
SELECT '10NC','2018-06-12',68
UNION ALL
SELECT '10NC','2018-06-13',35
UNION ALL
SELECT '210','2018-06-02',94
UNION ALL
SELECT '210','2018-06-04',100
UNION ALL
SELECT '210','2018-06-06',100
UNION ALL
SELECT '210','2018-06-07',93


;WITH CTE AS
(
SELECT 
    *
    ,RN = ROW_NUMBER() OVER (Partition by [Group] ORDER BY [DATE] DESC)
FROM @List
WHERE 
 [Date] >= '2018-06-01'
 AND [Group] in ('10', '10NC', '210') 
 And Number > 0
 )
 SELECT * FROM CTE WHERE RN = 1

注意:由于我没有足够的声誉在评论中提问,我直接将其张贴在答案中。