[sql问题]当group by type时,无法统计一个表中不

2017-04-01  本文已影响0人  脑仁儿与海

[详细描述]:

有如下表 table1:

————

id type

1  1

2  2

3  1

4  1

————

我们希望统计每个type的id数量.一般情况下我们会写出如下sql语句:

select type, count(id) from table1 group by type;

得出如下结果:

————

type count(id)

1    3

2    1

————

但本问题的实际需求为,type值有可能为(1,2,3),只是刚好这张表中没有type为3的数据.

所以我需要得到如下的结果方为正确:

————

type count(id)

1    3

2    1

3    0

————

关键在于如何统计数据中不存在的type为3的count(并为0).

我的解决方案为:

select ifnull(avg(type), 0), count(*) from table1 where type = 1

union all

select ifnull(avg(type), 0), count(*) from table1 where type = 2

union all

select ifnull(avg(type), 0), count(*) from table1 where type = 3

说明:此方案只限于运用在type可能值有限且不多的情况。

另外:ifnull函数在不同环境下要替换成相似功能的函数,如hql下的coalesce()函数

上一篇 下一篇

猜你喜欢

热点阅读