在SQL Server中,如何根据最后一次出现的系列更新值

时间:2015-03-12 18:33:28

标签: sql sql-server

我使用SQL Server中的LEAD()函数尽可能地获取。我有病人,实验室和约会。我已经弄清楚如何获得完成(准时)约会的最后状态和第二状态到最后状态。我的问题是在NEVER或EVENTUALLY之前将所有值更新为与最后一个条目相同。

EverDone Column
ON-TIME = the test was done 
EVENTUALLY = means the very next test was completed
NEVER = the last test was never done

我需要在EVENTUALLY之前将所有---设置为EVENTUALLY。例如2002年的LDL项目

我需要设置所有---在永远不要之前,例如BLOOD项目

但是标准不能是LDL测试中的最后一个系列。最后一次测试从未完成,但最终的状态已经完成。

Name           Item   date        Status    EverDone
----------------------------------------------------
ZZNIN, CHEEZE  BLOOD  6/6/2002    LAPSED    ---
ZZNIN, CHEEZE  BLOOD  1/6/2003    LAPSED    ---
ZZNIN, CHEEZE  BLOOD  7/8/2003    LAPSED    ---
ZZNIN, CHEEZE  BLOOD  6/15/2004   LAPSED    NEVER
SLAYER, JONES  LDL    8/19/2002   LAPSED    ---
SLAYER, JONES  LDL    10/2/2002   LAPSED    ---
SLAYER, JONES  LDL    12/12/2002  LAPSED    ---
SLAYER, JONES  LDL    12/12/2002  LAPSED    ---
SLAYER, JONES  LDL    12/16/2002  LAPSED    EVENTUALLY
SLAYER, JONES  LDL    12/26/2002  COMP      ON-TIME
SLAYER, JONES  LDL    1/8/2004    LAPSED    NEVER

1 个答案:

答案 0 :(得分:0)

如果您有主键,这将有效 -

UPDATE TableName
SET EverDone = 'EVENTUALLY'
WHERE KeyName in (SELECT b.KeyName 
                FROM TableName a
                  join TableName b on a.Name = b.Name 
                      and a.Item = b.Item 
                      and a.Date < b.Date
                      bEverDone = '---'
                WHERE a.EverDone = 'EVENTUALLY')

如果您没有主键,这将有效 -

UPDATE TableName
SET EverDone = 'EVENTUALLY'
WHERE CONCAT(Name, Item, Date) in (SELECT CONCAT(b.Name, b.Item, b.Date)
                FROM TableName a
                  join TableName b on a.Name = b.Name 
                      and a.Item = b.Item 
                      and a.Date < b.Date
                      bEverDone = '---'
                WHERE a.EverDone = 'EVENTUALLY')

但是 - 如果你的数据是这样的:

Name           Item   date        Status    EverDone
----------------------------------------------------
ZZNIN, CHEEZE  BLOOD  6/6/2002    LAPSED    ---
ZZNIN, CHEEZE  BLOOD  1/6/2003    LAPSED    ---
ZZNIN, CHEEZE  BLOOD  7/8/2003    LAPSED    ---
ZZNIN, CHEEZE  BLOOD  6/15/2004   LAPSED    NEVER
SLAYER, JONES  LDL    12/10/2001  LAPSED    ---
SLAYER, JONES  LDL    12/12/2001  LAPSED    ---
SLAYER, JONES  LDL    12/16/2001  LAPSED    ON-TIME    
SLAYER, JONES  LDL    8/19/2002   LAPSED    ---
SLAYER, JONES  LDL    10/2/2002   LAPSED    ---
SLAYER, JONES  LDL    12/12/2002  LAPSED    ---
SLAYER, JONES  LDL    12/12/2002  LAPSED    ---
SLAYER, JONES  LDL    12/16/2002  LAPSED    EVENTUALLY
SLAYER, JONES  LDL    12/26/2002  COMP      ON-TIME
SLAYER, JONES  LDL    1/8/2004    LAPSED    NEVER

Slayer-LDL-12/16/01之前的Slayer行也将更新。我假设没问题。