如果发生与2相同的值更新状态

时间:2018-09-18 12:51:22

标签: sql sql-server

我有一张桌子,如下所示。

ID  CustId  CustName Status
1     a1       A     NULL
2     a1       A     NULL
3     a2       B     NULL
4     a3       B     NULL
5     a4       C     NULL
6     a4       C     NULL
7     a5       D     NULL
8     a6       E     NULL

我想在第二次出现监视权时更新状态= 2,并且需要这样的输出...

ID  CustId  CustName Status
1     a1       A     1
2     a1       A     2
3     a2       B     1
4     a3       B     1
5     a4       C     1
6     a4       C     2
7     a4       D     2
8     a6       E     1

现在我正在使用以下查询来更新状态

update #tablename
set status= 2
where Custid in
(
  select * from
  (
    select Custid 
    from #tablename
    group by Custid 
    having count(*)> 1
  ) a
)

但是当count(custid)> 1时,上面的查询正在更新status = 2 我不想更新第一行。

2 个答案:

答案 0 :(得分:2)

CREATE TABLE #UserCompany
    ([ID] int, [CustId] varchar(2), [CustName] varchar(1), [Status] int)
;

INSERT INTO #UserCompany
    ([ID], [CustId], [CustName], [Status])
VALUES
    (1, 'a1', 'A', null),
    (2, 'a1', 'A', null),
    (3, 'a2', 'B', null),
    (4, 'a3', 'B', null),
    (5, 'a4', 'C', null),
    (6, 'a4', 'C', null),
    (7, 'a4', 'D', null),
    (8, 'a6', 'E', null)
;
select *,row_number() over (partition by [CustId] order by [ID]) as rn from #UserCompany

with cte as 
(
select *,row_number() over (partition by [CustId] order by [ID]) as rn from #UserCompany)
update cte 
set [Status]=case when rn > 1 then 2 else 1 end

UPDATE  b
SET     b.[Status] = a.[Status]
FROM    #UserCompany a
        INNER JOIN (select *,row_number() over (partition by [CustId] order by [ID]) as rn from #UserCompany) b
            ON a.id = b.id

答案 1 :(得分:0)

简介

解决此问题的最简单方法是使用子查询。

因此,对于每一行,您都会生成一个仅返回一个值的子查询。 此子查询基本上将计算ID> =当前客户ID的记录数(针对该客户ID)。

代码

UPDATE UserCompany 
SET
      UserCompany.status = temp.status
FROM usercompany AS u
INNER JOIN
  ( SELECT ID,
           CustID,
           CustName,

     (SELECT count(*)
      FROM UserCompany t
      WHERE t.custId = u.custId
        AND t.ID <= u.id ) AS status
   FROM UserCompany u ) AS TEMP ON temp.ID = u.ID;

   select * from UserCompany;

更新1:仅更新以前相同客户实例计数> = 2的记录

UPDATE UserCompany 
SET
      UserCompany.status = temp.status
FROM usercompany AS u
INNER JOIN
  ( SELECT ID,
           CustID,
           CustName,

     (SELECT count(*)
      FROM UserCompany t
      WHERE t.custId = u.custId
        AND t.ID <= u.id ) AS status
   FROM UserCompany u ) AS TEMP ON temp.ID = u.ID AND TEMP.STATUS >=2;

   select * from UserCompany;

更新2:与更新1相同,但设置为2而不是实际计数

(与上述相同,但插入2而不是实际计数)

UPDATE UserCompany 
SET
      UserCompany.status = temp.insert_status
FROM usercompany AS u
INNER JOIN
  ( SELECT ID,
           CustID,
           CustName,
     2 as insert_status, 
     (SELECT count(*)
      FROM UserCompany t
      WHERE t.custId = u.custId
        AND t.ID <= u.id ) AS status
   FROM UserCompany u ) AS TEMP ON temp.ID = u.ID AND TEMP.STATUS >=2;

   select * from UserCompany;