简体   繁体   中英

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.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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