Oracle / SQL - 计算单列中值的出现次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4729825/
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 08:56:24  来源:igfitidea点击:

Oracle / SQL - Count number of occurrences of values in a single column

sqloraclegroup-byaggregate-functions

提问by dscl

Okay, I probably could have come up with a better title, but wasn't sure how to word it so let me explain.

好吧,我可能想出一个更好的标题,但不知道如何措辞,所以让我解释一下。

Say I have a table with the column 'CODE'. Each record in my table will have either 'A', 'B', or 'C' as it's value in the 'CODE' column. What I would like is to get a count of how many 'A's, 'B's, and 'C's I have.

假设我有一个带有“CODE”列的表格。我表中的每条记录都将包含“A”、“B”或“C”,因为它是“CODE”列中的值。我想要的是计算我有多少个“A”、“B”和“C”。

I know I could accomplish this with 3 different queries, but I'm wondering if there is a way to do it with just 1.

我知道我可以用 3 个不同的查询来完成这个,但我想知道是否有办法只用 1 个来做到这一点。

回答by OMG Ponies

Use:

用:

  SELECT t.code,
         COUNT(*) AS numInstances
    FROM YOUR_TABLE t
GROUP BY t.code

The output will resemble:

输出将类似于:

code   numInstances
--------------------
A      3
B      5
C      1

If a code exists that has not been used, it will not show up. You'd need to LEFT JOIN to the table containing the list of codes in order to see those that don't have any references.

如果存在未使用的代码,则不会显示。您需要 LEFT JOIN 到包含代码列表的表才能查看那些没有任何引用的表。