我有一些数据库,例如下面的例子。
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分组,如下图所示?
答案 0 :(得分:3)
问题中对要求的描述不清楚,我猜测每个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 |
答案 1 :(得分:2)
一种方法是使用KEEP .. DENSE_RANK
查询1 :
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 C1
,C2
,MAX(N1) AS N1
,MAX(N2) KEEP (
DENSE_RANK FIRST ORDER BY N1 DESC
) AS N2
FROM TB
GROUP BY C1
,C2
<强> Results 强>:
| C1 | C2 | N1 | N2 |
|----|----|----|----|
| A | B | 2 | 2 |
| A1 | B1 | 3 | 1 |
| A2 | B2 | 1 | 6 |