计算不同的值

时间:2012-08-22 21:15:31

标签: mysql

数据库列:person,politicalViews,region

数据库示例:

person1  liberal      Lviv
person2  communistic  Donetsk
person3  liberal      Lviv
person4  conservative Kyiv
person5  conservative Odesa
person6  conservative Lviv
person7  communistic  Kyiv

预期栏目:地区,地区公民不同政治观点的数量,该地区的自由主义者人数,该地区保守派人数。 预期结果:

Lviv    2  2  1
Kyiv    2  0  1
Donetsk 1  0  0
Odesa   1  0  1

显然它看起来像这样:

SELECT region, ?????? FROM table GROUP BY region

我可以使用一些选择,但不是一个简单的方法吗?像DISTINCT(politicalViews)或COUNT(politicalViews,'liberal')

2 个答案:

答案 0 :(得分:2)

SELECT region, count(distinct politicalViews),
 sum(politicalViews='liberal'), sum(politicalViews='conservative')
FROM table GROUP BY region;

你为什么不想知道有多少共产党人?

答案 1 :(得分:2)

您可以使用聚合和GROUP BY

在一个查询中完成所有操作
select region,
  COUNT(DISTINCT pol_view) DiffView,
  sum(CASE WHEN pol_view = 'liberal' THEN 1 ELSE 0 END) NumberLiberals,
  sum(CASE WHEN pol_view = 'conservative' THEN 1 ELSE 0 END) NumberConservatives
from test
group by region

请参阅SQL Fiddle with Demo