gpt4 book ai didi

oracle - 如何列出具有一列最大值的行

转载 作者:行者123 更新时间:2023-12-04 01:59:56 24 4
gpt4 key购买 nike

我有一些数据库,如下例所示。

WITH TB AS(
SELECT 'A' C1, 'B' AS C2, 1 AS N1, 1 AS N2 FROM DUAL UNION ALL
SELECT 'A' C1, 'B' AS C2, 2 AS N1, 2 AS N2 FROM DUAL UNION ALL
SELECT 'A1' C1, 'B1' AS C2, 1 AS N1, 3 AS N2 FROM DUAL UNION ALL
SELECT 'A1' C1, 'B1' AS C2, 2 AS N1, 4 AS N2 FROM DUAL UNION ALL
SELECT 'A1' C1, 'B1' AS C2, 3 AS N1, 1 AS N2 FROM DUAL UNION ALL
SELECT 'A2' C1, 'B2' AS C2, 1 AS N1, 6 AS N2 FROM DUAL
)
SELECT * FROM TB

如何列出具有 Max(N1) 的所有行,并按 C1、C2 分组,如下图所示?

enter image description here

最佳答案

问题中的要求描述不清楚,我猜测应该为每组C1+c2计算max(n1)。
如果是这种情况,那么您可以这样使用 MAX() OVER () 解析函数:

SELECT tb.*,
max( n1 ) over (partition by c1, c2 ) xxxx
FROM TB;

| C1 | C2 | N1 | N2 | XXXX |
|----|----|----|----|------|
| A | B | 1 | 1 | 2 |
| A | B | 2 | 2 | 2 |
| A1 | B1 | 1 | 3 | 3 |
| A1 | B1 | 2 | 4 | 3 |
| A1 | B1 | 3 | 1 | 3 |
| A2 | B2 | 1 | 6 | 1 |

然后将上面的查询包装为子查询,并过滤掉不需要的行:

SELECT c1,c2,n1,n2 FROM (
SELECT tb.*,
max( n1 ) over (partition by c1, c2 ) xxxx
FROM TB
)
WHERE n1 = xxxx

| C1 | C2 | N1 | N2 |
|----|----|----|----|
| A | B | 2 | 2 |
| A1 | B1 | 3 | 1 |
| A2 | B2 | 1 | 6 |

演示:http://sqlfiddle.com/#!4/d2fb9/4

关于oracle - 如何列出具有一列最大值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49333940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com