带有where子句的SQL Update具有group by和having语句

时间:2017-04-24 20:46:40

标签: sql sql-server

我正在尝试更新与我的WHERE子句条件匹配的所有行的导出列,而不是更新所有行

这是我到目前为止所拥有的

 Create table Temp (
  Employeeid nvarchar(10),
  Punchtype nvarchar (2),
  Date Date,
  TotalTime decimal (16,2),
  Job nvarchar(10),
  Exported bit not null Default 0)

  Insert Into Temp (Employeeid,Punchtype,Date,TotalTime,Job)
  Values ('1234','C','4/24/2017',4,'J1234'), ('1234','RW','4/24/2017',4,'J1234'),('4563','C','4/24/2017',2,'J1234'), ('4563','C','4/24/2017',5,'J1234')

  Update temp set exported = 1 where exists ( select null from temp group by employeeid,Date,Job having Min(punchtype) = MAX(punchtype))

2 个答案:

答案 0 :(得分:2)

您可以使用CTE和窗口函数:

WITH CTE AS
(
    SELECT  *,
            MIN(punchtype) 
            OVER(PARTITION BY employeeid, [Date], Job) Min_punchtype,
            MAX(punchtype) 
            OVER(PARTITION BY employeeid, [Date], Job) Max_punchtype
    FROM Temp
)
UPDATE CTE
SET exported = 1
WHERE Min_punchtype = Max_punchtype
;

答案 1 :(得分:0)

尝试使用此更新:

Update temp set exported = 1 where temp.Employeeid = ( select temp.Employeeid from temp group by employeeid,Date,Job having Min(punchtype) = MAX(punchtype) );