获取 SQL Server 中列的频率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24767130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:13:54  来源:igfitidea点击:

Get frequency of a column in SQL Server

sqlsql-serverselectcount

提问by user_012314112

I have a column with values like 1,1,2,1,... and I would want to get the frequency of 1 and 2, I did

我有一列像 1,1,2,1,... 这样的值,我想得到 1 和 2 的频率,我做到了

SELECT count(column)
FROM table
WHERE column = 1;

SELECT count(column)
FROM table
WHERE column = 2;

But, could I take the frequency with a more direct way?

但是,我可以用更直接的方式获取频率吗?

回答by Cheruvian

Use aggregate functions

使用聚合函数

 Select column, count(*)
 From   table
 Group By column

This will return one row that contains the count, for each distinct value in column

对于列中的每个不同值,这将返回包含计数的一行

回答by Horaciux

One row each value:

每个值一行:

select column 'value', count (column) 'Frequency'
from table
group by column

if only 2 values this give you both results in one row

如果只有 2 个值,这会给你在一行中的两个结果

select sum(case when column=1 then 1 else 0 end) as '1 Frequency',
        sum(case when column=2 then 1 else 0 end) as '2 Frequency'
from table