table结构:name是主键
street有四个值:A,B,C,D
home_status有两个值:yes,no
sex有两个值:male,famale
age有四个值:20,40,45,other
要求是按街道查询出每条街道有多少人在家,
多少人不在家,男性20岁的,
男性40岁的,
男性45岁的,
男性其他岁数的,
所有男性的数量。女性20岁的,
女性40岁的,
女性45岁的,
女性其他岁数的,
所有女性的数量。所有人的数量显示在表格中就是以上这13列的数值,请教速度快的SQL语句。

解决方案 »

  1.   

    select sum(decode(home_status,'yes',1,0)) as 在家,sum(decode(home_status,'no',1,0)) as 不在家,
    sum(case when sex='male' and age='20' then 1 else 0 end) as 男性20岁的,
    sum(case when sex='male' and age='40' then 1 else 0 end) as 男性40岁的,
    sum(case when sex='male' and age='45' then 1 else 0 end) as 男性45岁的,
    sum(case when sex='male' and age='other' then 1 else 0 end) as 男性其他岁数的,
    sum(decode(sex,'male',1,0)) as 所有男性的数量
    ....//女的就是把前面男的male  换成  famale
    from table你测试下
      

  2.   

    这样多个group by 就可以了
    select street,
    sum(decode(home_status,'yes',1,0)) as 在家,
    sum(decode(home_status,'no',1,0)) as 不在家,
    sum(case when sex='male' and age='20' then 1 else 0 end) as 男性20岁的,
    sum(case when sex='male' and age='40' then 1 else 0 end) as 男性40岁的,
    sum(case when sex='male' and age='45' then 1 else 0 end) as 男性45岁的,
    sum(case when sex='male' and age='other' then 1 else 0 end) as 男性其他岁数的,
    sum(decode(sex,'male',1,0)) as 所有男性的数量
    from test
    group by street
      

  3.   

    谢谢狼哥。。请问有没有讲解这些SQL函数的资料?
      

  4.   

    我都是baidu查询,以及在csdn看的看到好的,自己也收藏了些!你这个sql用到的decode(字段,数值1,结果1,数值2,结果2...都不符合的结果)
    =
    case 字段 when 数值1 then 结果1 when 数值2 then 结果2 else 都不符合的结果 end
    或者
    case when 字段=数值1 then 结果1 when 字段=数值2 then 结果2 else 都不符合的结果 end