1

我正在做一个简单的 MySQL 查询,并希望使用 GROUP 为我的所有位置提供一组结果,而不必在每次运行查询时取消注释各个行。我对是否在 SELECT 或 WHERE 子句中使用 GROUP 感到困惑。

SELECT COUNT(*) FROM
Users AS u
-- Northern Ireland
WHERE u.postcode_area IN ('BT')
-- WALES
-- WHERE u.postcode_area IN ('CF','CH','GL')
-- Scotland
-- WHERE u.postcode_area IN ('AB','DD','DG','EH','FK')

所以作为一个结果,我想看到

  • 北爱尔兰 | 25678
  • 威尔士 | 34543
  • 苏格兰 | 4567
4

3 回答 3

2

你可以这样做:

SELECT 
    (CASE
        WHEN u.postcode_area IN ('BT') THEN 'Northern Ireland'
        WHEN u.postcode_area IN ('CF','CH','GL') THEN 'WALES'
        WHEN u.postcode_area IN ('AB','DD','DG','EH','FK') THEN 'Scotland'
        ELSE 'other') AS country,
    COUNT(*) 
FROM
    Users AS u
GROUP BY country
于 2013-08-28T09:17:08.110 回答
1

您可以像这样简单地尝试:

select 
  if(u.postcode_area in ('BT'), 'Northern Ireland', 
    if(u.postcode_area in ('CF','CH','GL'), 'Wales', 
      if(u.postcode_area in ('AB','DD','DG','EH','FK'), 'Scotland', 
        'Unknown'
      )
    )
  ) as label
  , count(*)
from Users as u
group by label

编辑:

顺便说一句,将包含 postcode_area 的表链接到标签会更整洁。

北爱尔兰 | 英国电信
威尔士 | CF
威尔士 | CH
威尔士 | GL
苏格兰 | AB
苏格兰 | DD
苏格兰 | DG
苏格兰 | EH
苏格兰 | FK

那么您的查询将是:

select
  pl.label,
  count(*) as count
from
  Users as u
  inner join containing postcode_area_label as pl
    on u.postcode_area = pl.postcode_area
group by
  pl.label
于 2013-08-28T09:18:43.363 回答
1

这将同时给出所有三个结果:

SELECT ireland.ireland_count, wales.wales_count, scotland.scotland_count FROM
(SELECT COUNT(*) as ireland_count FROM Users WHERE postcode_area IN ('BT')) as ireland
JOIN
(SELECT COUNT(*) as wales_count FROM Users WHERE postcode_area IN ('CF','CH','GL')) as wales
JOIN
(SELECT COUNT(*) as scotland_count FROM Users WHERE postcode_area IN ('AB','DD','DG','EH','FK')) as scotland;

输出将如下所示:

ireland_count   |   wales_count    |   scotland_count
25678           |   34543          |   4567
于 2013-08-28T09:19:01.533 回答