[英]SQL Server Comparing two rows in two different columns
ID Date I Date II
-----------------------------
1000 1/6/2016 2/3/2016
1000 1/28/2016 2/25/2016
1000 3/11/2016 4/8/2016
1000 4/8/2016 5/6/2016
1000 5/10/2016 6/7/2016
我想創建一個標志,告訴我2016年2月3日是否小於2016年2月28日,2016年2月25日小於3/11/2016,依此類推..在SQL Server中。
我該怎么做呢?
假設值正確存儲為日期,只需使用case
和lead()
:
select (case when date2 < lead(date1) over (partition by id order by date1)
then 1 else 0
end) as is_less_than
您可以使用以下鉛:
Select *,Flag = Case when [date II] < lead([date I]) over(partition by id order by [date I]) then 1 else 0 end
from #yourdate
輸出如下:
+------+------------+------------+------+
| Id | date I | date II | Flag |
+------+------------+------------+------+
| 1000 | 2016-01-06 | 2016-02-03 | 0 |
| 1000 | 2016-01-28 | 2016-02-25 | 1 |
| 1000 | 2016-03-11 | 2016-04-08 | 0 |
| 1000 | 2016-04-08 | 2016-05-06 | 1 |
| 1000 | 2016-05-10 | 2016-06-07 | 0 |
+------+------------+------------+------+
如果您使用SQL Server <2012,那么您可以使用如下查詢:
;With cte as (
Select *, RowN = Row_Number() over(partition by Id order by [date I]) from #yourdate
)
Select a.*, Flag = Case when a.[date II] < a1.[date I] then 1 else 0 end
from cte a left join cte a1
on a.RowN = a1.RowN - 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.