如何寫這個sql語句?
摘自:http://www.itpub.net/96851.html
表dept, emp
要得到如下結果
deptno, dname, employees
---------------------------------
10, accounting, clark;king;miller
20, research, smith;adams;ford;scott;jones
30, sales, allen;blake;martin;james;turners
也就是,每個dept的employee串起來作為一條記錄返回。
怎麼用一條sql語句完成?
答案如下:
/* Formatted on 2005/05/10 14:58 (Formatter Plus v4.8.5) */
SELECT deptno, dname, emps
FROM (SELECT d.deptno, d.dname,
RTRIM
( e.ename
|| ', '
|| LEAD (e.ename, 1) OVER (PARTITION BY d.deptno ORDER BY e.ename)
|| ', '
|| LEAD (e.ename, 2) OVER (PARTITION BY d.deptno ORDER BY e.ename)
|| ', '
|| LEAD (e.ename, 3) OVER (PARTITION BY d.deptno ORDER BY e.ename)
|| ', '
|| LEAD (e.ename, 4) OVER (PARTITION BY d.deptno ORDER BY e.ename)
|| ', '
|| LEAD (e.ename, 5) OVER (PARTITION BY d.deptno ORDER BY e.ename),
', '
) emps,
ROW_NUMBER () OVER (PARTITION BY d.deptno ORDER BY e.ename) x
FROM scott.emp e, scott.dept d
WHERE d.deptno = e.deptno)
WHERE x = 1
表dept, emp
要得到如下結果
deptno, dname, employees
---------------------------------
10, accounting, clark;king;miller
20, research, smith;adams;ford;scott;jones
30, sales, allen;blake;martin;james;turners
也就是,每個dept的employee串起來作為一條記錄返回。
怎麼用一條sql語句完成?
答案如下:
/* Formatted on 2005/05/10 14:58 (Formatter Plus v4.8.5) */
SELECT deptno, dname, emps
FROM (SELECT d.deptno, d.dname,
RTRIM
( e.ename
|| ', '
|| LEAD (e.ename, 1) OVER (PARTITION BY d.deptno ORDER BY e.ename)
|| ', '
|| LEAD (e.ename, 2) OVER (PARTITION BY d.deptno ORDER BY e.ename)
|| ', '
|| LEAD (e.ename, 3) OVER (PARTITION BY d.deptno ORDER BY e.ename)
|| ', '
|| LEAD (e.ename, 4) OVER (PARTITION BY d.deptno ORDER BY e.ename)
|| ', '
|| LEAD (e.ename, 5) OVER (PARTITION BY d.deptno ORDER BY e.ename),
', '
) emps,
ROW_NUMBER () OVER (PARTITION BY d.deptno ORDER BY e.ename) x
FROM scott.emp e, scott.dept d
WHERE d.deptno = e.deptno)
WHERE x = 1
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/267265/viewspace-82787/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 如何寫出高效能SQL語句SQL
- Java中如何解析SQL語句、格式化SQL語句、生成SQL語句?JavaSQL
- 一個JTextPane寫SQL語句的問題SQL
- sql語句抄寫作業SQL
- 優化SQL查詢:如何寫出高效能SQL語句優化SQL
- 學習筆記----一句SQL語句寫個乘法表筆記SQL
- SQL語句規範的寫法SQL
- OCI插入SQL語句的寫法SQL
- 一條SQL語句的書寫SQL
- 【sql】編寫基本的SQL SELECT語句四SQL
- 【sql】編寫基本的SQL SELECT語句三SQL
- 【sql】編寫基本的SQL SELECT語句一SQL
- SQL語句大全,你需要的SQL在這裡SQL
- sql語句如何執行的SQL
- SQL語句寫到累了?試試GreenDAOSQL
- MySQL中常用SQL語句的編寫MySql
- 【MySQL】經典資料庫SQL語句編寫練習題——SQL語句掃盲MySql資料庫
- SQL語句SQL
- 編寫高效 SQL 語句的最佳實踐SQL
- SQLServer效能優化之改寫SQL語句SQLServer優化
- 一個SQL語句的優化SQL優化
- SQL語句的4個階段SQL
- 我常用經典SQL語句[就先寫一句吧]SQL
- mysql 索引巧用,SQL語句寫得忒野了MySql索引
- 如何用SQL語句實現以下功能.SQL
- Oracle如何複製表的sql語句OracleSQL
- sql語句大全SQL
- 共享SQL語句SQL
- SQL語句整理SQL
- SQL基本語句SQL
- 精妙Sql語句SQL
- SQL語句集合SQL
- oracle sql語句OracleSQL
- sql語句 求救!SQL
- SQL精妙語句SQL
- SQL語句收集SQL
- 常用SQL語句SQL
- sql常用語句SQL