db2 select中使用case替代行转列操作

来源:互联网 发布:企业网络搭建 编辑:程序博客网 时间:2024/05/16 17:53

在DB2中进行行转列比较麻烦,这里我在select里用case语法代替行转列操作

 

 

BILL_HEADERS 为单据主表,一条记录代表一条单据,表结构如下

CHECK_UNIT varchar(120) 公司

BOE_DEPT_ID number(100) 部门

BOE_DATE timpstamp 提交时间

 

表中数据如下(例子)

NO 公司            部门     提交时间

1    深圳分公司  财务部  2007-7-20-12.00.00.000000

2    深圳分公司  财务部  2007-7-20-13.00.00.000000

3    深圳分公司  开发部  2007-7-20-13.06.00.000000

4    北京分公司  公关部  2007-9-20-13.00.00.000000

5    北京分公司  公关部  2007-10-20-13.00.00.000000

 

一个公司下有多个部门

现在查询各个公司下的每个部门在星期天到星期六的单据数,星期一到星期六的单据数分开统计,

 要求查询结果结构如下

公司           部门      单据总数    星期天 星期一 星期二 星期三 星期四 星期五 星期六
深圳分公司  财务部   31            0        5        7        2        11      6        0
深圳分公司  开发部   46            0        7        23      7         3       5        1
深圳分公司  外贸部   9              0        1        3        3         1       1        0
珠海分公司  业务部   1              0        0        0        0         1       0        0
北京分公司  公关部   43            8        7        1        12       5       10      0
北京分公司  内务部   30            3        0        0        11       3       12      1

 

使用以下查询语句可以实现

 

select t.CHECK_UNIT as 公司,
       t.BOE_DEPT_ID as 部门,
       sum(t.total) as 单据总数,
       sum(t.seven) as 星期天,
       sum(t.one) as 星期一,
       sum(t.two) as 星期二,
       sum(t.three) as 星期三,
       sum(t.four) as 星期四,
       sum(t.five) as 星期五,
       sum(t.six) as 星期六
  from (select bh.CHECK_UNIT,
               bh.BOE_DEPT_ID,
               count(*) as total,
               count(case
                       when (DAYOFWEEK(bh.BOE_DATE) = 1) then
                        1
                     end) as seven,
               count(case
                       when (DAYOFWEEK(bh.BOE_DATE) = 2) then
                        1
                     end) as one,
               count(case
                       when (DAYOFWEEK(bh.BOE_DATE) = 3) then
                        1
                     end) as two,
               count(case
                       when (DAYOFWEEK(bh.BOE_DATE) = 4) then
                        1
                     end) as three,
               count(case
                       when (DAYOFWEEK(bh.BOE_DATE) = 5) then
                        1
                     end) as four,
               count(case
                       when (DAYOFWEEK(bh.BOE_DATE) = 6) then
                        1
                     end) as five,
               count(case
                       when (DAYOFWEEK(bh.BOE_DATE) = 7) then
                        1
                     end) as six
          from sie.SIE_BOE_HEADERS bh
         where bh.BOE_DATE > TIMESTAMP('2007-7-20-12.00.00.000000')
         group by bh.CHECK_UNIT, bh.BOE_DEPT_ID, DAYOFWEEK(bh.BOE_DATE)) t
 group by t.CHECK_UNIT, t.BOE_DEPT_ID;

 

原创粉丝点击