我有一个包含如下数据的表:
pK Customer DateTime1 DateTime2
1 6 2016-04-01 00:00:00.000 2016-10-09 00:00:00.000
2 6 2016-07-01 00:00:00.000 2016-10-21 00:00:00.000
3 6 2016-10-01 00:00:00.000 2016-10-20 00:00:00.000
我想查找行,当订购DateTime1时,相应的DateTime2值(在客户ID上过滤时)不遵循相同的顺序。
所以在上面的例子中,我想找到pK 3的行,因为DateTime1按升序排序,然后DateTime2不大于第2行的DateTime2。
它似乎与这个问题相似,但它处理项目的顺序而不是不平等: TSQL check if specific rows sequence exists
我尝试使用CTE声明版本
答案 0 :(得分:2)
Declare @YourTable table (pK int,Customer int,DateTime1 datetime,DateTime2 datetime)
Insert Into @YourTable values
(1,6,'2016-04-01 00:00:00.000','2016-10-09 00:00:00.000'),
(2,6,'2016-07-01 00:00:00.000','2016-10-21 00:00:00.000'),
(3,6,'2016-10-01 00:00:00.000','2016-10-20 00:00:00.000')
;with cte as (
Select *,Flg=Row_Number() over (Partition By Customer Order By DateTime1) - Row_Number() over (Partition By Customer Order By DateTime2)
From @YourTable
)
Select pK
,Customer
,DateTime1
,DateTime2
From cte
Where Flg>0
返回
pK Customer DateTime1 DateTime2
3 6 2016-10-01 00:00:00.000 2016-10-20 00:00:00.000
答案 1 :(得分:0)
这似乎是row_number()
:
select t.*
from (select t.*,
row_number() over (partition by customer order by datetime1) as seqnum_1,
row_number() over (partition by customer order by datetime2) as seqnum_2
from t
) t
where seqnum_1 <> seqnum_2;
但是这将返回所有错误排序的行,基于全局排序(在这种情况下为pk 2和3)。
您只想知道给定行上方向的变化。为此,请使用lag()
:
select t.*
from (select t.*,
lag(datetime1) over (partition by customer order by pk) as prev_dt1,
lag(datetime2) over (partition by customer order by pk) as prev_dt2
from t
) t
where (dt1 > prev_dt1 and dt2 <= prev_dt2) or
(dt1 < prev_dt1 and dt2 >= prev_dt2);