简体   繁体   中英

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

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.

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.

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.

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