如果count(id)在表中有多个列,则更新列

fcy6dtqo  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(249)

我有一张像这样的table。。

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

我想更新 status = 2 什么时候 count(custid) > 1 以及 status = 1 什么时候 count(custid) = 1 我希望输出如下

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
f4t66c6m

f4t66c6m1#

用这个。

SELECT tbl.id
      ,tbl.cust_id
      ,tbl.cust_name
      ,(SELECT COUNT(cust_id)
        FROM Mytable
        WHERE cust_id = tbl.cust_id) AS status
FROM MyTable tbl;
-- to update table
-- first create a dummy table
create table tbl as select tbl.id, tbl.cust_id, tbl.cust_name, (select count(cust_id) from Mytable where cust_id = tbl.cust_id) as status from MyTable tbl;
-- drop original
drop table mytable;
-- rename dummy
alter table tbl rename to mytable;
a2mppw5e

a2mppw5e2#

WITH CTE
(
select custid,count(1) cnt
from my_table
group by custid
)
UPDATE a SET a.status= CASE WHEN b.cnt = 1 THEN 1 ELSE 2 END
FROM my_table a
INNER JOIN CTE b
on a.custid=b.custid
de90aj5v

de90aj5v3#

试试这个:

declare @tbl table (ID int,  CustId char(2), CustName char(1), Status int);
insert into @tbl 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,'a5','D',NULL),
(8,'a6','E',NULL);

update t1 set t1.Status = case when t2.st > 1 then 2 else 1 end
from @tbl t1
join (select ID, COUNT(*) over (partition by custname) st from @tbl) t2
on t1.ID = t2.ID

select * from @tbl
ecr0jaav

ecr0jaav4#

使用联接更新:
它将在sql server中工作:

update tablename set status=cstatus
from tablename inner join
(
select custid, count(custid) as cstatus
from tablename)b on tablename.custid=b.custid

在mysql中,以下命令将起作用

UPDATE tablename
    JOIN (
    select custid, count(custid) as cstatus
    from tablename)b on tablename.custid=b.custid
SET set status=cstatus

相关问题