group by 擴充套件函式實現報表的需求

2021-06-25 08:53:00 字數 2580 閱讀 6643

drop table t;

create table t(order_date date,--訂購日期

order_no number,--訂購號

order_book varchar2(10),--訂購書籍

order_fee number,--訂單總金額

order_num number--訂單明細數目

);insert into t

select date '2010-5-1'+level,

trunc(dbms_random.value*1000),

'book1',100*level,level

from dual

connect by level<5;

insert into t

select date '2010-6-1'+level,

trunc(dbms_random.value*1000),

'book2',200*level,level

from dual

connect by level<5;

commit;

/*題目:要求在每組order_book內,按日期公升序排列(order_no排序不管),常規分組在前,小計在後,合計最後。

根據結果可以看出,對於book1來說,前4行就是標準分組,即*/

select t.order_date

,t.order_no

,t.order_book

,sum(t.order_fee) sum_order_fee

,sum(t.order_num) sum_order_num

from t

group by t.order_book,t.order_date,t.order_no

order by order_book,order_date

/*第5行小計可以看做是group by order_book,然後橫跨order_time,order_no列的小計,所以也就是*/ 

select null

,null

,t.order_book

,sum(t.order_fee) sum_order_fee

,sum(t.order_num) sum_order_num

from t

group by t.order_book

order by order_book

/*根據上面兩點,可以想到組合列分組,rollup(t.order_book,(t.order_date,t.order_no)),排序是order by order_book,order_date

即*/

select t.order_date

,t.order_no

,t.order_book

,sum(t.order_fee) sum_order_fee

,sum(t.order_num) sum_order_num

from t

group by rollup(t.order_book,(t.order_date,t.order_no))

order by t.order_book,t.order_date

/*最後結合grouping_id來分組*/

select t.order_date

,t.order_no

,t.order_book

,sum(t.order_fee) sum_order_fee

,sum(t.order_num) sum_order_num

,grouping_id(t.order_date,t.order_no,t.order_book)

from t

group by rollup(t.order_book,(t.order_date,t.order_no))

order by t.order_book,t.order_date

----------------結合上面的結果,使用decode進行報**式化

select decode(grouping_id(t.order_date,t.order_no,t.order_book),6,order_book||'小計',

7,'合計',

to_char(t.order_date,'yyyy-mm-dd')) order_date

,t.order_no

,decode(grouping_id(t.order_date,t.order_no,t.order_book),0,order_book,

null) rder_book

,sum(t.order_fee) sum_order_fee

,sum(t.order_num) sum_order_num

from t

group by rollup(t.order_book,(t.order_date,t.order_no))

order by t.order_book,t.order_date

Hive高階聚合函式 group by擴充套件

目錄 指定多種聚合的維度 層次,對多個group by union all進行替換 簡化 可實現從右到左遞減多級的統計,顯示統計某一層次結構的聚合 可以實現多個任意維度的查詢,會統計所選列中值的所有組合的聚合 按照一定規則給統計的各維度組合打標,並返回標識值。1.group by擴充套件 group...

報表設計 自由報表 自由擴充套件

一 新建資料來源 參照網格式報表設計 二 操作步驟 在b3單元格中填寫 ds.select empcode 設定為縱向擴充套件 在b4單元格中填寫 ds.orgcode 在d3單元格中填寫 ds.empname 在d4單元格中填寫 ds.orgname 自由擴充套件定義 主格定義 a1的左主格手工設...

詭異的Group by函式

select 表2.name,count id 管理員from 表2 where 表2.name in select name from 表1 group by 表2.name 使用上面這個語句sql通常會報錯 訊息 8120,級別 16,狀態 1,第 1 行 列 表2.管理員 在選擇列表中無效,因...