简体   繁体   English

SQL-计算列中的出现次数

[英]SQL - count occurrences in a column

I would like to count values in a column (col2) that contains strings so that the a new column (count) returns the number of strings. 我想对包含字符串的列(col2)中的值进行计数,以便新列(计数)返回字符串的数量。

For example: 例如:

col1 | col2 | count
1    | dog  |  1
2    | cat  |  2
3    | cat  |  2
4    | bird |  1

... ...

Standard SQL offers window functions that do this: 标准SQL提供了执行此操作的窗口函数:

select col1, col2, count(*) over (col2) as cnt
from t;

If, you are working with Microsoft SQL Server, then you could use below SQL Script 如果您正在使用Microsoft SQL Server,则可以使用下面的SQL脚本

SELECT col1,
       col2,
       COUNT(col2) OVER(PARTITION BY col2) AS cnt
FROM <table_name>
ORDER BY col1;

Result : 结果:

col1 col2   cnt
1    dog    1
2    cat    2
3    cat    2
4    bird   1

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

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