有关SQL查询的指导

时间:2012-09-18 12:02:55

标签: sql sql-server sql-server-2008

我有下表,我需要将Check_Status从Completed更新为'Not Completed'以获取特定Prod_ID的最大Transaction_ID:

Tran_ID     Prod_ID    Check_Status
-------     --------   ------------
107893      XA         Completed
107892      XA         Completed
107891      XA         Completed
107890      XB         Completed
107889      XB         Completed
107888      YC         Completed
107887      YC         Completed
107886      YC         Completed
107885      YC         Completed

我的结果应显示如下,即产品ID XA的最大传输ID为107893,应更新为“未完成”。剩下的事情应该保持不变。同样适用于其他产品ID XBXC

Tran_ID    Prod_ID     Check_Status
-------    --------    ------------
107893     XA          Not-Completed
107892     XA          Completed
107891     XA          Completed
107890     XB          Not-Completed
107889     XB          Completed
107888     YC          Not-Completed
107887     YC          Completed
107886     YC          Completed
107885     YC          Completed

3 个答案:

答案 0 :(得分:3)

您可以使用CTE:

;with cte as
(
  select tran_id, prod_id,
    row_number() over(partition by prod_id order by tran_id desc) rn,
    check_status
  from yourtable
) 
update  cte
set check_status = 'Not-Completed'
where rn = 1

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

     UPDATE Transactions set 
    Check_Status= 'Not completed' 
     where Tran_ID IN (
        Select MAX(Tran_ID) as Tran_ID from 
Transactions Group by Prod_ID)

答案 2 :(得分:1)

UPDATE tablename t1 
SET t1.Check_Status = 'Not-Completed'
WHERE t1.TranId IN 
    (
       SELECT Max(Tran_ID) 
       FROM Tablename t2 
       GROUP BY Prod_ID
    )