構建測試表:
sql**
create
table table1
(
id integer,
name varchar2(10)
)
create
table table2
(
id integer,
role varchar2(10)
)
insert
into table1 (id, name) values (1, '張三');
insert
into table1 (id, name) values (2, '李四');
commit;
insert
into table2 (id, role) values (1, '查詢');
insert
into table2 (id, role) values (1, '分析');
insert
into table2 (id, role) values (1, '決策');
insert
into table2 (id, role) values (2, '查詢');
commit;
create table table1
(id integer,
name varchar2(10)
)create table table2
(id integer,
role varchar2(10)
)insert into table1 (id, name) values (1, '張三');
insert into table1 (id, name) values (2, '李四');
commit;
insert into table2 (id, role) values (1, '查詢');
insert into table2 (id, role) values (1, '分析');
insert into table2 (id, role) values (1, '決策');
insert into table2 (id, role) values (2, '查詢');
commit;
要求輸出結果:
sql**
id name role
1 張三 查詢,分析,決策
2 李四 查詢
id name role
1 張三 查詢,分析,決策
2 李四 查詢
方法
一、使用wmsys.wm_concat
sql**
select table1.*,wmsys.wm_concat(role) from table1,table2 where table1.id=table2.id
group
by table1.id,table1.name
select table1.*,wmsys.wm_concat(role) from table1,table2 where table1.id=table2.id
group by table1.id,table1.name
方法
二、使用sys_connect_by_path
sql**
select id, name, ltrim(max(sys_connect_by_path(role, ',')), ',') from
(select row_number() over(partition by table1.id order
byname) rn,table1.*, role from table1, table2 where table1.id =
table2.id)
start with rn = 1
connect
byprior rn = rn - 1 and
prior id = id
group
by id, name
order
by id
select id, name, ltrim(max(sys_connect_by_path(role, ',')), ',') from
(select row_number() over(partition by table1.id order by name) rn,table1.*, role from table1, table2 where table1.id =
table2.id)
start with rn = 1
connect by prior rn = rn - 1 and prior id = id
group by id, name
order by id
方法
三、使用自定義函式
sql**
create
orreplace
function my_concat(mid in
integer) return varchar2 --記住:引數和返回值裡的資料型別都不用定義長度
isresult varchar2(4000); --定義變數,記住oracle中定義變數不需要
begin
for temp_cursor in (select role from table2 where id=mid) loop --此處在游標for迴圈中使用查詢
result :=result || temp_cursor.role || ','; --oracle中字元連線使用||,而sql server中用+
end loop;
result := rtrim(result,','); --去掉最後乙個空格,還有oracle中的賦值前面沒有set
return result;
end;
select table1.*,my_concat(table1.id) from table1,table2 where table1.id=table2.id
group
by table1.id,table1.name
order
by table1.id
原文:
oracle實現行列轉換
ql select from student idname chinese math english 1a 90 70 80 2b 80 70 90 3c 80 90 70 select id,name,chinese 課程,chinese 分數 from student union all sel...
SQL 實現行列轉換
今天有個有這樣的需求,那就看看這個例項吧 create table tb 姓名 varchar 10 課程 varchar 10 分數 int insert tb select 張三 語文 60 union all select 張三 數學 70 union all select 張三 英語 80 ...
SQL實現行列轉換 MySQL
示例資料 tablename為col index 實現行列轉換的統計結果 sql語句 select c2,sum case when c3 正式 then 1else 0end as 正式 sum case when c3 臨時 then 1else 0end as 臨時 from col inde...