SQL查询多条记录显示为一条的处理办法
2009-01-14 15:17
375 查看
最近在网上老是遇到一些同行求将多条记录按规则显示为一条的信息,现整理如下:
create table test_1
(
col1 varchar2(4),
col2 varchar2(4),
col3 varchar2(4),
col4 varchar2(4)
);
insert into test_1 values('123','t1','s','p1');
insert into test_1 values('123','t1','s','p2');
insert into test_1 values('124','c1','s','p3');
insert into test_1 values('124','c1','s','p4');
SQL> select * from test_1;
COL1 COL2 COL3 COL4
---- ---- ---- ----
123 t1 s p1
123 t1 s p2
124 c1 s p3
124 c1 s p4
下面的语句实现将结果变为 123 t1 s p1,p2
124 c1 s p3,p4
SQL>
SQL> select col1, col2, col3, substr(max(sys_connect_by_path(col4, ',')), 2) aa
2 from (select col1,
3 col2,
4 col3,
5 col4,
6 col1 || col2 || col3 || col5 col5,
7 col1 || col2 || col3 || col6 col6
8 from (select col1,
9 col2,
10 col3,
11 col4,
12 rank() over(partition by col1, col2, col3 order by col4) col5,
13 rank() over(partition by col1, col2, col3 order by col4) - 1 col6
14 from test_1))
15 start with substr(col5, -1) = 1
16 connect by prior col5 = col6
17 group by col1, col2, col3
18 ;
COL1 COL2 COL3 AA
---- ---- ---- --------------------------------------------------------------------------------
123 t1 s p1,p2
124 c1 s p3,p4
create table test_1
(
col1 varchar2(4),
col2 varchar2(4),
col3 varchar2(4),
col4 varchar2(4)
);
insert into test_1 values('123','t1','s','p1');
insert into test_1 values('123','t1','s','p2');
insert into test_1 values('124','c1','s','p3');
insert into test_1 values('124','c1','s','p4');
SQL> select * from test_1;
COL1 COL2 COL3 COL4
---- ---- ---- ----
123 t1 s p1
123 t1 s p2
124 c1 s p3
124 c1 s p4
下面的语句实现将结果变为 123 t1 s p1,p2
124 c1 s p3,p4
SQL>
SQL> select col1, col2, col3, substr(max(sys_connect_by_path(col4, ',')), 2) aa
2 from (select col1,
3 col2,
4 col3,
5 col4,
6 col1 || col2 || col3 || col5 col5,
7 col1 || col2 || col3 || col6 col6
8 from (select col1,
9 col2,
10 col3,
11 col4,
12 rank() over(partition by col1, col2, col3 order by col4) col5,
13 rank() over(partition by col1, col2, col3 order by col4) - 1 col6
14 from test_1))
15 start with substr(col5, -1) = 1
16 connect by prior col5 = col6
17 group by col1, col2, col3
18 ;
COL1 COL2 COL3 AA
---- ---- ---- --------------------------------------------------------------------------------
123 t1 s p1,p2
124 c1 s p3,p4
相关文章推荐
- SQL--处理表重复记录(查询和删除) 示例:查询最近一条用户登陆日志
- 查询最新一条记录的处理办法
- SQL--处理表重复记录(查询和删除) 示例:查询最近一条用户登陆日志
- 关于SQL中查询重复字段只显示一条记录
- SQL根据Id来查询一条记录或全部记录
- 一个SQL按照类别各取一条记录查询问题
- Oracle数据库SQL查询重复记录的处理
- 使用一条sql查询多个表中的记录数
- SQL 合并多条记录成一条记录
- 【数据库】SQL查询多条不重复记录值简要解析
- 使用distinct在mysql中查询多条不重复记录值的解决办法
- SQL同样的记录只显示一条
- mysql中查询多条不重复记录值的解决办法
- SQLite一条SQL语句插入多条记录
- 一条SQL语句,关于字符分割关联多条记录的问题
- SQL查询重复数据,只显示一条sql语句
- 一条SQL查询访问记录表(visit_log)中某个类目(catalog_id)的访问量(visit)排前两名的记录行
- Mysql查询最近一条记录的sql语句(优化篇)
- 根据某个字段将多条记录的某个字段拼接成一个字段(SQL查询)
- SQL查询多条不重复记录值(有借鉴意义)