这是我的数据:
liza
liza
liza
alex
alex
alex
liza
我想更新此表,其中包含每个名称的每次出现的数据,如下所示:
liza 4
liza 4
liza 4
alex 3
alex 3
alex 3
liza 4
到目前为止,我有:
update table set column2=count(name) group by name
非常感谢你的帮助
答案 0 :(得分:5)
update T1 set
Column2 = T2.C
from YourTable as T1
inner join (
select count(*) as C, Name
from YourTable
group by Name
) as T2
on T1.Name = T2.Name
带有表变量的示例
declare @YourTable table
(
Name varchar(10),
Column2 int
)
insert into @YourTable (Name) values
('liza'),('liza'),('liza'),('alex'),('alex'),('alex'),('liza')
update T1 set
Column2 = T2.C
from @YourTable as T1
inner join (
select count(*) as C, Name
from @YourTable
group by Name
) as T2
on T1.Name = T2.Name
在这里试试。 http://data.stackexchange.com/stackoverflow/q/102392/update-with-count
以下是使用CTE和count(*) over()
的另一种方式。
declare @YourTable table
(
Name varchar(10),
Column2 int
)
insert into @YourTable (Name) values
('liza'),('liza'),('liza'),('alex'),('alex'),('alex'),('liza')
;with cte as
(
select Column2,
count(*) over(partition by Name) as C
from @YourTable
)
update cte set
Column2 = C
这个查询你可以在这里试试。 http://data.stackexchange.com/stackoverflow/q/102394/update-with-count-2