我有一个数据表(EMP), 结构如下ORG_ID(组织的ID,相当于主键) , ORG_NM(组织名字), EMP_CLS(员工分类),EMP_ID(员工ID)
一个组织有N个员工,员工有三种不能状态, 用EMP_CLS 表示
EMP_CLS有三种状态, 用1, 2, 3 数字表示, 我想用SQL语句显示为下面的效果:ORG_NM| 人数(这个组织共有多少人数,EMP_CLS=1时)EMP_ACCOUNT1| (EMP_CLS=2时)EMP_ACCOUNT2|EMP_ACCOUNT3|
      |                                                |                          |            |
      |                                                |                          |            |
      |                                                |                          |            |
      |                                                |                          |            |EMP_ACCOUNT1 EMP_ACCOUNT2 EMP_ACCOUNT3 分别是员工状态为EMP_CLS=1,EMP_CLS=2,EMP_CLS3的员工共有多少人,怎么用SQL语句表示出来, 
先谢谢大家了, 

解决方案 »

  1.   

    try it ...
    select distinct
           e.ORG_ID,
           e.ORG_NM,
           sum(case when e.EMP_CLS = 1 
                    then 1
                    else 0
                end) over(partition by e.ORG_ID,e.ORG_NM) as EMP_ACCOUNT1,
           sum(case when e.EMP_CLS = 2 
                    then 1
                    else 0
                end) over(partition by e.ORG_ID,e.ORG_NM) as EMP_ACCOUNT2,
           sum(case when e.EMP_CLS = 3 
                    then 1
                    else 0
                end) over(partition by e.ORG_ID,e.ORG_NM) as EMP_ACCOUNT3
      from EMP e;
      

  2.   

    这样       e.ORG_ID, e.ORG_NM,显示起来,会不会有多行重复呢?
      

  3.   

    2楼的差不多,不过我会用group by 代替 distinct,我总感觉distinct慢select e.ORG_ID,
           e.ORG_NM,
           sum(case when e.EMP_CLS = 1 
                    then 1
                    else 0
                end) as EMP_ACCOUNT1,
           sum(case when e.EMP_CLS = 2 
                    then 1
                    else 0
                end)  as EMP_ACCOUNT2,
           sum(case when e.EMP_CLS = 3 
                    then 1
                    else 0
                end)  as EMP_ACCOUNT3
      from EMP e group by e.ORG_ID,e.ORG_NM
    ;
      

  4.   

    新的问题, 在下面
    http://topic.csdn.net/u/20071107/20/288918ff-35a0-4f49-8263-846ec7add838.html
    跟这个差不多, 还能不能给我想一下