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

时间:2018-09-17 06:09:54

标签: mysql sql sql-server

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

for filename in all_csv_files:
    %run 'Volatility_Spreadsheet_Prepare.py' $filename

我想在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

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

使用连接进行更新:

它将在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

答案 2 :(得分:1)

尝试一下:

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

答案 3 :(得分:1)

使用它。

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;