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

2021-05-02 03:59:57 字數 2382 閱讀 3344

在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

1end) as seven,

count(case

when (dayofweek(bh.boe_date) = 2) then

1end) as one,

count(case

when (dayofweek(bh.boe_date) = 3) then

1end) as two,

count(case

when (dayofweek(bh.boe_date) = 4) then

1end) as three,

count(case

when (dayofweek(bh.boe_date) = 5) then

1end) as four,

count(case

when (dayofweek(bh.boe_date) = 6) then

1end) as five,

count(case

when (dayofweek(bh.boe_date) = 7) then

1end) 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;

DB2 SELECT語句高階用法

db2 create tabel語句高階用法 說明 不好意思,把標題寫錯了,寫成 db2 select 語句高階用法 太搞笑了,剛才發現,改過來了。一般的create table 就不說了,就說說三種高階的 1 建立結果表 create table new table name as select ...

DB2 SELECT語句高階用法

db2 create tabel語句高階用法 說明 不好意思,把標題寫錯了,寫成 db2 select 語句高階用法 太搞笑了,剛才發現,改過來了。一般的create table 就不說了,就說說三種高階的 1 建立結果表 create table new table name as select ...

db2locate函式 DB2中使用locate

db2中的like的使用是有限制的,它後面不能跟乙個變數或者是字段,因此,在儲存過程或sql語句中就不能like乙個變數或乙個字段。比如有兩個表a a,b,c,d b a,b,c,d 普遍的用法是 select from a where a.b like 張 此語句在任何資料庫都是通用的,但有時也遇...