SQL全部打印在一排

问题描述 投票:0回答:3

我想在两列打印数据,如:统计范畴

但是,我的代码打印所有一行,如:计数分类计数范畴

有小费吗?

Select sum(Case when population >= 1000000 and population < 5000000 then 1 else 0 end) as Count, '1 000 000 - 4 999 999' as Category,
   sum(Case when population >= 500000 and population < 100000 then 1 else 1 end) as Count, '100 000 - 499 999' as Category,
   sum(Case when population >= 500000 and population < 100000 then 1 else 1 end) as Count, '500 000 - 999 999' as Category,
   sum(Case when population >= 500000 and population < 100000 then 1 else 1 end) as Count, 'Under 100 000' as Category,
   sum(Case when population >= 500000 and population < 100000 then 1 else 1 end) as Count, 'Over 5 million' as Category
from cities
mysql
3个回答
0
投票
Select sum(Case when population >= 1000000 and population < 5000000 then 1 else 0 end) as Count, '1 000 000 - 4 999 999' as Category FROM cities
UNION 
SELECT sum(Case when population >= 500000 and population < 100000 then 1 else 1 end) as Count, '100 000 - 499 999' as Category FROM cities

等等...

所有的毗连单一的结果与UNION关键字一个结果表

你的情况下,部分其他应无处不0而不是1,如果你只是想算城市...一个更好的解决反正会

SELECT COUNT(cities.primKey) as Count, '1 000 000 - 4 999 999' as Category FROM cities WHERE population >= 1000000 and population < 5000000
UNION
SELECT COUNT(cities.primKey) as Count, '1 000 000 - 4 999 999' as Category FROM cities WHERE population >= 500000 and population < 100000
UNION ...

0
投票
SELECT CASE WHEN Population >= 5000000
            THEN 'Over 5 million' 
            WHEN Population >= 1000000 AND Population < 5000000
            THEN '1 000 000 - 4 999 999'
            WHEN Population >= 500000 AND Population < 1000000
            THEN '500 000 - 999 999' 
            WHEN Population >= 100000 AND Population < 500000
            THEN '100 000 - 499 999'
            WHEN Population < 100000
            THEN 'Under 100 000'
       END [Category]
       ,COUNT(*) [Count]
FROM Cities

0
投票

如果你想获得的所有类别即使有属于它没有任何城市,你可以这样做:

select sum(if(ci.population is null, 0, 1)) as 'Count', cat.Category
from (
  select 0 as 'low', 100000 as 'high', 'Under 100 000' as Category, 1 as 'ord'
  union
  select 100000, 499999, '100 000 - 499 999', 2
  union
  select 500000, 999999, '500 000 - 999 999', 3
  union
  select 1000000, 4999999, '1 000 000 - 4 999 999', 4
  union
  select 5000000, null, 'Over 5 million' , 5
) as cat
  left join cities ci on ci.population between cat.low and ifnull(cat.high, ci.population)
group by cat.Category, cat.ord
order by cat.ord
© www.soinside.com 2019 - 2024. All rights reserved.