使用分析函数 Oracle 分组

Posted

技术标签:

【中文标题】使用分析函数 Oracle 分组【英文标题】:Group by using Analytical function Oracle 【发布时间】:2014-09-04 19:39:28 【问题描述】:

我有以下演示代码。 我怎样才能得到想要的输出。它只是没有出现在我的脑海中:-(。它必须是一个简单的改变。

WITH Abc  AS (SELECT 'AB' AS code,'Z12' AS des, 123 AS tk FROM dual UNION
SELECT 'AB','Z14',234 FROM dual UNION
SELECT 'ACB','D12',34 FROM dual UNION
SELECT 'ACB','D12',36 FROM dual UNION
SELECT 'ACB','F12',35 FROM dual UNION
SELECT 'ABX','G44',243 FROM dual UNION
SELECT 'ABX','H44',654 FROM dual UNION
SELECT 'ABX','J12',534 FROM dual UNION
SELECT 'ABQ',NULL,356 FROM dual)

SELECT DISTINCT tk,code,des ,code||'_'||row_number () OVER (PARTITION BY code ORDER BY code,des ) AS str FROM abc
ORDER BY 2,3;

输出:

 tk code des str
--- --- --- ---
123 AB  Z12 AB_1
234 AB  Z14 AB_2
356 ABQ     ABQ_1
243 ABX G44 ABX_1
654 ABX H44 ABX_2
534 ABX J12 ABX_3
34  ACB D12 ACB_1  ---  ACB_1
36  ACB D12 ACB_2  ----I want ACB_1 here too since desc is same for that code
35  ACB F12 ACB_3

【问题讨论】:

【参考方案1】:
**USE RANK() instead of rownumber()**


WITH Abc  AS (SELECT 'AB' AS code,'Z12' AS des, 123 AS tk FROM dual UNION
SELECT 'AB','Z14',234 FROM dual UNION
SELECT 'ACB','D12',34 FROM dual UNION
SELECT 'ACB','D12',36 FROM dual UNION
SELECT 'ACB','F12',35 FROM dual UNION
SELECT 'ABX','G44',243 FROM dual UNION
SELECT 'ABX','H44',654 FROM dual UNION
SELECT 'ABX','J12',534 FROM dual UNION
SELECT 'ABQ',NULL,356 FROM DUAL)

SELECT DISTINCT TK,CODE,DES ,CODE||'_'||rank() OVER (PARTITION BY CODE ORDER BY CODE,DES ) AS STR FROM ABC
ORDER BY 2,3;

【讨论】:

非常感谢..确实有效,令人惊讶的是我在使用排名之前尝试过,但没有成功,也许我做错了什么。

以上是关于使用分析函数 Oracle 分组的主要内容,如果未能解决你的问题,请参考以下文章

Oracle-分析函数_总结

Oracle分析函数入门

Oracle 分析函数 ROW_NUMBER() 使用

Oracle 分析函数的汇总

Oracle分析函数入门

Oracle分析函数入门