0

I have a table called registrations from which I want to know the total count by city in the following layout.

Expected Layout

enter image description here

Tried preparing the below sql statement which gives me the correct information but not in the correct layout.

SELECT COUNT(IF(city LIKE '%location 1%',1, NULL)) 'LOCATION 1',
       COUNT(IF(city LIKE '%location 2%',1, NULL)) 'LOCATION 2',
       COUNT(IF(city LIKE '%location 3%',1, NULL)) 'LOCATION 3'
FROM registrations;

The layout from the above query.

Current Layout

enter image description here

How do I re-write the query to return the expected layout?

Nick
  • 138,499
  • 22
  • 57
  • 95
h4kl0rd
  • 625
  • 1
  • 10
  • 23

2 Answers2

2

You need to write the query as a UNION to get the results in the format you want:

SELECT 'LOCATION 1' AS location, COUNT(IF(city LIKE '%location 1%',1, NULL)) AS `count`
FROM registrations
UNION
SELECT 'LOCATION 2', COUNT(IF(city LIKE '%location 2%',1, NULL))
FROM registrations
UNION
SELECT 'LOCATION 3', COUNT(IF(city LIKE '%location 3%',1, NULL))
FROM registrations
Nick
  • 138,499
  • 22
  • 57
  • 95
  • How could I automate this for future registrations from different cities? – h4kl0rd Apr 19 '19 at 13:18
  • @h4kl0rd are the city names exact matches? i.e. do you really need to use `LIKE`, or could you just use `=`? – Nick Apr 20 '19 at 01:22
1

Use GROUP BY:

SELECT (CASE WHEN city LIKE '%location 1%' THEN 'LOCATION 1',
             WHEN city LIKE '%location 2%' THEN 'LOCATION 2',
             WHEN city LIKE '%location 3%' THEN 'LOCATION 3'
        END) as location,
       COUNT(*)
FROM registrations
GROUP BY location;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786