SQL选择更改日期

时间:2018-02-13 18:56:35

标签: sql sql-server date ssms

我在SSMS中有一张表:

Id  Date Value
111 1/1  x
111 1/2  x
111 1/3  y
111 1/4  y
111 1/5  x
111 1/6  x
222 1/3  z
222 1/5  x
222 1/7  x

我想保留值更改日期的记录。所以输出将是:

Id  Date Value
111 1/1  x
111 1/3  y
111 1/5  x
222 1/3  z
222 1/5  x

查询此内容的好方法是什么?

非常感谢!

2 个答案:

答案 0 :(得分:1)

使用lag()

select t.*
from (select t.*, lag(value) over (partition by id order by date) as prev_value
      from t
     ) t
where prev_value is null or prev_value <> value;

答案 1 :(得分:1)

您也可以试试这个。

DECLARE @MyTable TABLE(Id  INT, Date VARCHAR(3) , Value VARCHAR(3) )
INSERT INTO @MyTable VALUES
(111, '1/1', 'x'), 
(111, '1/2', 'x'), 
(111, '1/3', 'y'), 
(111, '1/4', 'y'), 
(111, '1/5', 'x'), 
(111, '1/6', 'x'), 
(222, '1/3', 'z'), 
(222, '1/5', 'x'), 
(222, '1/7', 'x')

;WITH CTE AS (
    SELECT  * ,
        ROW_NUMBER() OVER(PARTITION BY Id Order by [Date]) AS RN 
    FROM @MyTable
)
SELECT T1.* 
FROM CTE T1
    LEFT JOIN CTE T2 ON T1.Id = T2.Id AND T1.RN = ( T2.RN + 1 )
WHERE T1.Value <> T2.Value
    OR T2.Id IS NULL

结果:

Id          Date Value
----------- ---- -----
111         1/1  x    
111         1/3  y    
111         1/5  x    
222         1/3  z    
222         1/5  x