SQL 比较行

SQL compare row

我正在寻找一个存储过程来逐行比较 table。例如,我有一个 table

id | fruit  | farmer |     plant_time      |  status
-------------------------------------------------------
1  | banana | John   | 2021-02-02 18:00:01 |   true
2  | apple  | Steve  | 2021-02-02 18:00:30 |   true   <<<<
3  | apple  | Steve  | 2021-02-02 18:01:10 |   true   <<<<  flag to false
4  | orange | Steve  | 2021-02-02 18:01:50 |   true

我想找出同一个水果同一个农民之间的差异 plant_time 不超过一分钟并将状态标记为 false。

提前致谢

I want to find out same fruit same farmer and the difference between plant_time not more than one minute and flag the status to false.

在任何受支持的 SQL 服务器版本中,您可以使用 lag()lead()。正如你表达的问题:

select t.*,
       (case when lead(planttime) over (partition by farmer order by planntime) < dateadd(minute, 1, planttime)
             then 'false' else 'true'
        end) as status
from t;

如果要更新值,可以使用可更新的 CTE:

with toupdate as (
      select t.*,
             (case when lead(planttime) over (partition by farmer order by planntime) < dateadd(minute, 1, planttime)
                   then 'false' else 'true'
              end) as new_status
      from t
     )
update toupdate
    set status = new_status
    where status is null or status <> new_status;

请注意,您可以 在 SQL Server 2008 中使用 apply 或相关子查询执行此操作。但是,我怀疑您没有使用不受支持的商业软件。

其次,通常是这样的序列中的 第一个 被标记,而不是最后一个。在这种情况下,您将使用 lag() 而不是 lead()(并调整时间比较)。