简体   繁体   English

为 SQL Server 中的列中的每个值计算冗余

[英]Count redundant for each value in a column in SQL server

If I have the following table in a SQL Server 2019 database as follows:如果我在 SQL Server 2019 数据库中有下表,如下所示:

|id   | name   | count  |
+-----+--------+--------+
| 1   | rose   |   1    |
| 2   | peter  |   1    |
| 3   | ann    |   1    |
| 4   | rose   |   2    |
| 5   | ann    |   2    |
| 6   | ann    |   3    |
| 7   | mike   |   1    |

I would like to find out if an inserted name already exists in the column "name" and how many times and right a count next to it as shown in "count" column.我想知道插入的名称是否已经存在于“名称”列中,以及“计数”列中显示的在它旁边的计数有多少次和正确。 For example when ann was inserted the second time I put count value bext to it which is 2, and ann was inserted the third time I put 3 next to it.例如,当第二次插入 ann 时,我将计数值放在它旁边,即 2,第三次插入 ann 时,我将 3 放在它旁边。

How to do that using SQL?如何使用 SQL 做到这一点?

Thank you谢谢

Here is one approach using the insert ... select syntax:这是使用insert ... select语法的一种方法:

insert into mytable (name, cnt)
select v.name, (select count(*) + 1 from mytable t where t.name = v.name)
from (values (@name)) v(name)

The value to insert is given as @name in derived table values() .要插入的值在派生表values()作为@name给出。 Then we use a subquery to count how many such names already exist in the table.然后我们使用子查询来计算表中已经存在多少这样的名字。

I would suggest that you calculate this information when you query the table, rather than when you insert rows:我建议您在查询表时计算此信息,而不是在插入行时计算:

select t.*,
       row_number() over (partition by name order by id) as count
from t;

The value will always be correct -- even when the data is updated or rows are deleted.该值将始终正确——即使在更新数据或删除行时也是如此。

Select Name, Count(*) 
From Table
Group By Name 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM