1.建立行轉列通用儲存過程
sql**:create or replace procedure row_to_col(tabname in varchar2,
group_col in varchar2,
column_col in varchar2,
value_col in varchar2,
aggregate_func in varchar2 default 'max',
colorder in varchar2 default null,
roworder in varchar2 default null,
when_value_null in varchar2 default null,
viewname in varchar2 default 'v_tmp')
authid current_user as
sqlstr varchar2(2000) := 'create or replace view ' || viewname ||
' as select ' || group_col || ' ';
c1 sys_refcursor;
v1 varchar2(100);
begin
open c1 for 'select distinct ' || column_col || ' from ' || tabname || case when colorder is not null then ' order by ' || colorder end;
loop
fetch c1
into v1;
exit when c1%notfound;
sqlstr := sqlstr || chr(10) || ',' || case
when when_value_null is not null then
'nvl('
end || aggregate_func || '(decode(to_char(' || column_col ||
'),''' || v1 || ''',' || value_col || '))' || case
when when_value_null is not null then
chr(44) || when_value_null || chr(41)
end || '"' || v1 || '"';
end loop;
close c1;
sqlstr := sqlstr || ' from ' || tabname || ' group by ' || group_col || case
when roworder is not null then
' order by ' || roworder
end;
execute immediate sqlstr;
end row_to_col;
tabname需要進行行轉列操作的表名,檢視也可以;
group_col查詢結果要按某列或某些列分組的欄位名;
column_col要從行轉成列的字段;
value_col需要聚合的值字段;
aggregate_func選用的聚合函式,可選,預設為max;
colorder行轉列後列的排序,可選;
roworder行轉列後記錄的排序,可選;
when_value_null若value_col欄位的值聚合後為空,則轉換成該值,可選;
viewname建立的檢視名稱,可選,預設為v_tmp。
2.建立測試資料
sql**:
create table rowtocol_test as
select 2009 year,1 month,'部門1' dept,50000 expenditure from dual
union all select 2009,2,'部門1',20000 from dual
union all select 2009,2,'部門1',30000 from dual
union all select 2010,1,'部門1',35000 from dual
union all select 2009,2,'部門2',40000 from dual
union all select 2009,3,'部門2',25000 from dual
union all select 2010,2,'部門3',60000 from dual
union all select 2009,2,'部門3',15000 from dual
union all select 2009,2,'部門3',10000 from dual;
3.驗證
4.擴充套件:對於檢視的測試
Oracle行轉列通用過程
create orreplace procedure row to col tabname invarchar2 group col invarchar2 column col invarchar2 value col invarchar2 aggregate func invarchar2 def...
Mysql動態行轉列(不使用儲存過程)
資料 行轉列後的資料 sql如下 示例 建立 create table dome id intnot null auto increment testdate date default null comment 時間 testtext varchar 50 default null comment ...
通用儲存過程
alter proc dbo pagination pagesize int 10 每頁顯示的記錄數 pagecurrent int 1 當前要顯示的頁號 fdname varchar 100 主鍵名或者標識列名 selectstr varchar 2000 select子句,不包含select關鍵...