有数据表:字段为:单位、工种、姓名、性别、年龄
如何统计如下信息:
单位     工种   >25岁男  >25岁女   >40岁男  >40岁女
车间一  工种一  
车间二  工种二
...谢谢

解决方案 »

  1.   


    create table #(uDept varchar(10), uType varchar(10), uSex bit, uAge int)
    insert into # select '1','1',0,25
    insert into # select '1','2',0,25
    insert into # select '1','1',0,36
    insert into # select '2','1',0,26
    insert into # select '2','1',0,40
    insert into # select '2','1',1,52
    insert into # select '2','1',0,46select uDept, uType, 
    Age25Sex0 = (select count(uAge) from # where uDept = A.uDept and uType = A.uType and uAge between 25 and 39 and uSex = 0),
    Age25Sex1 = (select count(uAge) from # where uDept = A.uDept and uType = A.uType and uAge between 25 and 39 and uSex = 1),
    Age40Sex0 = (select count(uAge) from # where uDept = A.uDept and uType = A.uType and uAge between 40 and 55 and uSex = 0),
    Age40Sex1 = (select count(uAge) from # where uDept = A.uDept and uType = A.uType and uAge between 40 and 55 and uSex = 1)
    from # A
    group by uDept, uType--drop table #
    /*
    uDept      uType      Age25Sex0   Age25Sex1   Age40Sex0   Age40Sex1
    ---------- ---------- ----------- ----------- ----------- -----------
    1          1          2           0           0           0
    1          2          1           0           0           0
    2          1          1           0           2           1(3 行受影响)
    */
      

  2.   

    *--如果SQL SERVER表
    --大于25岁包括40岁以上的
    select 单位,工种, 
    sum(case when 年龄>25 and 性别='男' then 1 else 0 end) as '〉25岁男', 
    sum(case when 年龄>25 and 性别='女' then 1 else 0 end) as '〉25岁女', 
    sum(case when 年龄>40 and 性别='男' then 1 else 0 end) as '〉40岁男', 
    sum(case when 年龄>40 and 性别='女' then 1 else 0 end) as '〉40岁女' 
    from 表 
    group by 单位,工种 --大于25岁不包括40岁以上的
    select 单位,工种,
    sum(case when 年龄>25 and 年龄<=40 and 性别='男' then 1 else 0 end) as '〉25岁男',
    sum(case when 年龄>25 and 年龄<=40 and 性别='女' then 1 else 0 end) as '〉25岁女',
    sum(case when 年龄>40 and 性别='男' then 1 else 0 end) as '〉40岁男',
    sum(case when 年龄>40 and 性别='女' then 1 else 0 end) as '〉40岁女'
    from 表
    group by 单位,工种*--如果DBF表
    --大于25岁包括40岁以上的select 单位,工种,;
    sum(IIF(年龄>25 and 性别='男',1,0) as '〉25岁男',;
    sum(IIF(年龄>25 and 性别='女',1,0) as '〉25岁女',; 
    sum(IIF(年龄>40 and 性别='男',1,0) as '〉40岁男',; 
    sum(IIF(年龄>40 and 性别='女',1,0) as '〉40岁女'; 
    from 表; 
    group by 单位,工种 --大于25岁不包括40岁以上的
    select 单位,工种,;
    sum(IIF(年龄>25 and 年龄<=40 and 性别='男',1,0) as '〉25岁男',;
    sum(IIF(年龄>25 and 年龄<=40 and 性别='女',1,0) as '〉25岁女',; 
    sum(IIF(年龄>40 and 性别='男',1,0) as '〉40岁男',; 
    sum(IIF(年龄>40 and 性别='女',1,0) as '〉40岁女'; 
    from 表; 
    group by 单位,工种