在SQL中,如何不选择列值与其上方行中的值相同的行

时间:2016-08-23 16:17:15

标签: sql sql-server tsql

我有一个包含列值和时间戳的表。价值每秒都在不断变化。所以我的数据如下

V1 T1
V1 T2
V2 T3
V3 T4..

等等。所以时间戳会不断增加,但是值可以与它们不变的相同。 我想只选择值与前一行不同的行。 所以我想减少数据并只选择数据发生变化的记录。 有人会知道怎么做吗?

2 个答案:

答案 0 :(得分:2)

这仅适用于SQL Server 2012或更高版本

WITH cte AS (
    SELECT
        V,T,
        LAG(V) OVER (ORDER BY T) AS LAST_V
    FROM
        TABLE
    )
SELECT
    V, T
FROM
    cte
WHERE
    V <> LAST_V OR LAST_V IS NULL;

LAST_V是前一行中V的值,由T排序。因此,如果V&lt;&gt; LAST_V表示V与所提出的LAST_V不同。 LAST_V IS NULL表示您位于第一行。

答案 1 :(得分:1)

Declare @YourTable table (Col1 varchar(25),Col2 varchar(25))
Insert Into @YourTable values
('V1','T1'),
('V1','T2'),
('V2','T3'),
('V3','T4')

;with cteBase as (
    Select *,RowNr=Row_Number() over(Partition By Col1 Order By Col2 Desc) From @YourTable
)
Select * from cteBase where RowNr=1

返回

Col1    Col2    RowNr
V1      T2      1
V2      T3      1
V3      T4      1
  

或者您可以使用With Ties条款

Select Top 1 With Ties *
  From @YourTable
  Order By Row_Number() over(Partition By Col1 Order By Col2 Desc)

返回

Col1    Col2
V1      T2  
V2      T3  
V3      T4    
相关问题