5

A have a column named key - 1,1,2,2,2,2,3 Now i do it with 3 querys:

SELECT count(key) as k FROM `test` WHERE key=1
SELECT count(key) as k FROM `test` WHERE key=2
SELECT count(key) as k FROM `test` WHERE key=3

How to count in one query how many 1,2,3?

Meg Lepett
  • 71
  • 1
  • 1
  • 6
  • Does this answer your question? [Count the occurrences of DISTINCT values](https://stackoverflow.com/questions/1346345/count-the-occurrences-of-distinct-values) – mickmackusa Apr 20 '21 at 09:32

4 Answers4

10

Use group by:

SELECT `key`, COUNT(*) FROM `test` GROUP BY `key`;
fabien
  • 1,529
  • 1
  • 15
  • 28
1

you can do like this

select count(key) as K FROM test where key in (1,2,3)
Aman Varshney
  • 820
  • 1
  • 9
  • 26
1

This is another option:

SELECT sum(key=1) as k1, sum(key=2) as k2,sum(key=3) as k3 FROM `test`

you could also add a group by column if the values of key were part of some other group.

Boice
  • 156
  • 1
  • 7
0

Try this

SELECT  COUNT(Key) as K
        FROM 
        test 
        GROUP BY Key
commit
  • 4,777
  • 15
  • 43
  • 70