用于计数的SQL语句

时间:2019-04-19 13:00:58

标签: mysql sql

我有一个名为registrations的表,在下面的布局中,我想从中了解城市总数

预期的布局

enter image description here

尝试准备下面的sql语句,该语句可为我提供正确的信息,但布局不正确。

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;

上述查询的布局。

当前布局

enter image description here

如何重新编写查询以返回预期的布局?

2 个答案:

答案 0 :(得分:2)

您需要将查询写为UNION才能以所需的格式获得结果:

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

答案 1 :(得分:1)

使用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;