这个网上把例子拿来的,当然这里只是另外做个例子,其实,11g中有更好的解决方式,有个pivot函数.在我这个帖子中有介绍,这里就当大家再熟悉下10g中处理类似问题的方法吧。
http://www.cnblogs.com/miley/archive/2010/04/16/1713327.html
源表:
NUM DR_ID PE_ID SEQ_NUM DOB_DATE NAME
10 10 10 10 07-11-01 Wang
10 11 12 13 08-02-09 Li
10 12 13 14 08-02-09 Qian
11 15 16 17 08-08-27 Du
11 22 23 45 08-05-19 Dong
11 33 55 88 07-11-01 Xia
查询结果;
num, dr1_dob_dt, dr1_name, dr2_dob_dt, dr2_name, dr3_dob_dt, dr3_name
10 07-11-01 Wang 08-02-09 Li 08-02-09 Qian
11 08-08-27 Du 08-05-19 dong 07-11-01 Xia
12 01_11_01 ZHAO
也就是要将num 相同的 DOB_DT, NAME 查出来放在同一行
script:
create table driver (num number, dr_id number, pe_id, number, seq_num number, dob_date date, name varchar2(10));
insert into driver values (10, 10, 10, 10, to_date('07_11_01', 'YY_MM_DD'), 'WANG');
insert into driver values (10, 11, 12, 13, to_date('08_02_09', 'YY_MM_DD'), 'lI');
insert into driver values (10, 12, 13, 14, to_date('06_12_01', 'YY_MM_DD'), 'QIANG');
insert into driver values (11, 15, 16, 17, to_date('07_11_01', 'YY_MM_DD'), 'DONG');
insert into driver values (11, 18, 19, 10, to_date('02_11_01', 'YY_MM_DD'), 'DU');
insert into driver values (11, 20, 21, 23, to_date('05_11_01', 'YY_MM_DD'), 'XIA');
insert into driver values (12, 14, 33, 34, to_date('01_11_01', 'YY_MM_DD'), 'ZHAO');
SQL:
其实 MAX(decode(rn, 1, dob_date, NULL)) 跟MAX(decode(rn, 1, dob_date))是一样的,根据Oracle文档:
The DECODE function is allowed in SQL but not PL/SQL statements. A DECODE function compares expr to each search value one by one. If expr is equal to a search, Oracle returns the corresponding result. If no match is found, Oracle returns default, or, if default is omitted, returns null.
SQL> SELECT num,
2 MAX(decode(rn, 1, dob_date, NULL)) dob_date1,
3 MAX(decode(rn, 1, name, NULL)) name1,
4 MAX(decode(rn, 2, dob_date, NULL)) dob_date2,
5 MAX(decode(rn,2, name, NULL)) name2,
6 MAX(decode(rn, 3, dob_date, NULL)) dob_date3,
7 MAX(decode(rn, 3, name, NULL)) name3
8 FROM (SELECT num,
9 dr_id,pe_id,seq_num,dob_date,name,
10 row_number() over(PARTITION BY num ORDER BY dr_id) AS rn
11 FROM driver) t
12 GROUP BY num
13 ORDER BY 1;
NUM DOB_DATE1 NAME1 DOB_DATE2 NAME2 DOB_DATE3 NAME3
---------- ----------- ---------- ----------- ---------- ----------- ----------
10 2007/11/1 WANG 2008/2/9 lI 2006/12/1 QIANG
11 2007/11/1 DONG 2002/11/1 DU 2005/11/1 XIA
12 2001/11/1 ZHAO