将表emp输出'10 clark king miller'

简介: 摘自:http://tkyte.blogspot.com/Suppose someone asks you:I need to take the results of a query and pivot a value.

摘自:http://tkyte.blogspot.com/

Suppose someone asks you:

I need to take the results of a query and pivot a value. That is, I would like output from the EMP table to look like this:

DEPTNO ENAMES
------- ------------
10 clark king miller
20 adams ford …

can this be done in just SQL?

With the addition of analytic functions in Oracle 8i Release 2 and the SYS_CONNECT_BY_PATH() function in Oracle 9i Release 1 – this became something we can in fact do rather easily in SQL. The approach we will take is:

  1. Partition the data by DEPTNO and within each DEPTNO sort the data by ENAME and assign a sequential number using the ROW_NUMBER() analytic function
  2. So, we end up with a record eventually that is the result of connecting 1 to 2 to 3 to 4 and so on for each DEPTNO
  3. The SYS_CONNECT_BY_PATH() function will return the list of ENAMES concatenated together for us.

The query would look like this:

SQL> select deptno,
2 max(sys_connect_by_path(ename, )) scbp
3 from (select deptno, ename,
row_number() over
(partition by deptno order by ename) rn
4 from emp
5 )
6 start with rn = 1
7 connect by prior rn = rn-1 and prior deptno = deptno
8 group by deptno
9 order by deptno
10 /

DEPTNO SCBP
---------- ----------------------------------------
10 CLARK KING MILLER
20 ADAMS FORD JONES SCOTT SMITH
30 ALLEN BLAKE JAMES MARTIN TURNER WARD

I used to use STRAGG for this (prior to sys_connect_by_path and analytics) - but now find this approach preferable.

[@more@]
目录
相关文章
|
1月前
|
SQL 数据库
INTO SELECT
【11月更文挑战第10天】
24 3
|
1月前
|
存储 SQL 关系型数据库
SELECT INTO
【11月更文挑战第08天】
27 2
|
7月前
|
SQL 数据库管理
SQL基础题----基本的SELECT语句、order by排序
SQL基础题----基本的SELECT语句 ambiguous 模糊
226 1
可以使用 UNION 或者 UNION ALL 来合并多个 SELECT 语句的结果
可以使用 UNION 或者 UNION ALL 来合并多个 SELECT 语句的结果
265 7
|
数据库 索引
SELECT
SELECT
69 0
|
关系型数据库 MySQL 测试技术
软件测试mysql面试题:对于表Employee_Details中的Employee_Name‘yuhan‘,如何将‘Salary‘字段的值更改为7500?
软件测试mysql面试题:对于表Employee_Details中的Employee_Name‘yuhan‘,如何将‘Salary‘字段的值更改为7500?
83 0
|
SQL
表复制:SELECT INTO 和 INSERT INTO SELECT
表复制:SELECT INTO 和 INSERT INTO SELECT
166 0