sql多条件统计

下面这种查询就是多条件统计

假设现在我们要统计某个社区每栋楼每个年龄段的人数。

年龄段的范围是我们自己制定的,所以作为确定条件,我们把它当作字段名的列。

每个社区有几栋楼是不一定的,作为不确定条件,我们把它放在最左侧的数据项中。

这样查询结果的样子大可以想象出来了吧现出来了。

拆开来看就会变的明白了!!

如果你只统计小区内每个楼的人数?

很明显列表中楼是作为数据查询出来的,这时候可以借助group by.

group by 查询出来的数据会显示在数据列表中,你也不需要考虑有多少栋楼。

select  s.sname,count(s.*) 
    FROM storied_building s 
    INNER JOIN building b ON s.id = b.storied_buildid 
    INNER JOIN people p ON p.buildid = b.id  
    where s.communityid = 1 group by s.sname;

(中间的关联你可以忽略)

只统计每个小区内各个年龄段的人数?

各个年龄段要成为字段名,我们使用 count函数和case来完成我们的需求

select  count(case when p.age between 0 and 10 then p.age end) as age1,
    count(case when p.age between 11 and 20 then p.age end) as age2,
    count(case when p.age between 21 and 30 then p.age end) as age3,
    count(case when p.age between 31 and 40 then p.age end) as age4,
    count(case when p.age between 41 and 50 then p.age end) as age5,
    count(case when p.age between 51 and 120 then p.age end) as age6
    FROM storied_building s 
    INNER JOIN building b ON s.id = b.storied_buildid 
    INNER JOIN people p ON p.buildid = b.id  
    where s.communityid = 1 ;

将以上两个查询合并成一个查询!

select  s.sname,
    count(case when p.age between 0 and 10 then p.age end) as age1,
    count(case when p.age between 11 and 20 then p.age end) as age2,
    count(case when p.age between 21 and 30 then p.age end) as age3,
    count(case when p.age between 31 and 40 then p.age end) as age4,
    count(case when p.age between 41 and 50 then p.age end) as age5,
    count(case when p.age between 51 and 120 then p.age end) as age6 
    FROM storied_building s 
    INNER JOIN building b ON s.id = b.storied_buildid 
    INNER JOIN people p ON p.buildid = b.id  
    where s.communityid = 1 group by s.sname;

总结:
说多条件统计,实际上最多也就两个条件了,两个条件必有一个作为数据项,还有一个作为字段名,这样就得到了我们的结果表,一般不确定统计条件有多少项的就作为数据项,可以确定统计条件项的就作为字段名。

你可能感兴趣的:(sql)