UPDATE表具有不同的ID但相同的DisplayNum

时间:2013-07-01 13:48:34

标签: sql-server sql-server-2008

我有一个名为tblData的表,其中包含以下数据。

查询之前:

   ID DisplayNum   Called
    1     A1        NULL
    2     A1        NULL
    3     A1        NULL
    4     B4        NULL
    5     B4        NULL

我现在有:

UPDATE TOP (1) tblData SET Called = GETDATE() WHERE DisplayNum = @DisplayNo AND Called IS NULL

ID DisplayNum   Called
1     A1        7/1/2013 9:00 AM
2     A1        7/1/2013 9:00 AM
3     A1        7/1/2013 9:00 AM
4     B4        7/1/2013 9:30 AM
5     B4        7/1/2013 9:30 AM

我只想更新那个特定DisplayNum

的被调用为null的顶级记录
ID DisplayNum   Called
1     A1        7/1/2013 9:00 AM
2     A1        7/1/2013 9:05 AM
3     A1        7/1/2013 9:08 AM
4     B4        7/1/2013 9:20 AM
5     B4        7/1/2013 9:26 AM

如果该特定组的ID不同,我该如何获取?

4 个答案:

答案 0 :(得分:1)

我是否正确地想要使用仍然满足WHERE条件的最低ID更新记录?

尝试

UPDATE tblData 
  SET Called = GETDATE() 
  WHERE DisplayNum = @DisplayNo AND Called IS NULL
    AND ID = (SELECT TOP 1 ID FROM tblData WHERE DisplayNum = 'A1' AND Called IS NULL ORDER BY ID ASC)

答案 1 :(得分:1)

update  a 
set a.Called = GETDATE() 
from tblData a join (select min(ID) ID, DisplayNum 
                     from test
                     group by DisplayNum) b 
on (a.ID = b.ID and a.DisplayNum = b.DisplayNum)
where a.Called is NULL;

答案 2 :(得分:1)

UPDATE T
SET Called = GETDATE()
FROM tblData T
    INNER JOIN
        (SELECT ID, ROW_NUMBER(PARTITION BY DisplayNum ORDER BY ID) correlative
         FROM tblData
         WHERE Called IS NULL AND DisplayNum = @DisplayNo) TD ON T.ID=TD.ID
WHERE TD.correlative=1

答案 3 :(得分:0)

根据问题中的当前信息,应该没有问题(除非您多次调用UPDATE)。这是SQL Fiddle上的一个deom。

以下是一种不使用TOP执行更新的方法:

DECLARE @@DisplayNo varchar(2)
SELECT @@DisplayNo = 'A1'

;WITH tblRN AS
(
  SELECT *,
    ROW_NUMBER() OVER(PARTITION BY DisplayNum 
                      ORDER BY ID) AS RowNum
  FROM tblData
)

UPDATE tblRN
  SET CALLED = GETDATE()
WHERE
  DisplayNum = @@DisplayNo AND
  CALLED IS NULL AND
  RowNum = 1