在MySQL中对结果进行分组

时间:2013-08-28 09:07:22

标签: mysql group-by

我正在做一个简单的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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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的表链接到标签会更简洁。

北爱尔兰| BT
威尔士| 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

答案 2 :(得分: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