我有一张如下表所示的表格:
cust_id/frequency
01/null
01/null
02/null
02/null
01/null
03/null
04/null
04/null
03/null
用频率更新表后,它应显示如下
cust_id/frequency
01/3
01/3
02/2
02/2
01/3
03/2
04/2
04/2
03/2
我已经尝试过以下查询,但它只显示我想要的结果,而不是更新表。
select cust_id, count(*) as frequency
from table A
group by cust_id
order by count(*) desc
有没有任何查询可以帮助我更新,因为我有10000加上cust_id?
非常感谢你花时间看我的问题。
答案 0 :(得分:2)
SQL Server有一个非常好的功能,即CTE(和子查询)可以更新。您可以使用可更新的CTE和窗口函数执行您想要的操作:
with toupdate as (
select t.*, count(*) over (partition by cust_id) as newfrequency
from table t
)
update toupdate
set frequency = newfrequency;
答案 1 :(得分:1)
这样的事情:
UPDATE t1
SET t1.frequency = cnt
FROM tbl t1
JOIN (SELECT cust_id,
Count(1) cnt
FROM tbl
GROUP BY cust_id) t2
ON t1.cust_id = t2.cust_id
答案 2 :(得分:1)
试试这个 -
DECLARE @temp TABLE
(
cust_id CHAR(2),
frequency INT
)
INSERT INTO @temp (cust_id)
VALUES
('01'), ('01'), ('02'), ('02'),( '01'),
('03'), ('04'), ('04'), ('03')
;WITH cte AS
(
SELECT cust_id, cnt = COUNT(1)
FROM @temp
GROUP BY cust_id
)
UPDATE @temp
SET frequency = cnt
FROM cte
WHERE cte.cust_id = [@temp].cust_id
SELECT * FROM @temp
输出 -
cust_id frequency
------- -----------
01 3
01 3
02 2
02 2
01 3
03 2
04 2
04 2
03 2