1

可能重复:
通过嵌套连接选择最高 Seq 号

您好,我要写一个查询,我想为每个客户 ID 取最大的序列号(大序列号将根据最高的银行账户余额计算)。

请考虑此表有 100000 条记录。

表格如下 -

桌子:

  
**ClID** **SeqNu** **Bal**  
1 1 30000  
1 2 26789  
1 3 23456  
1 4 12345  
1 5 21234  
2 3 12456  
2 4 45632  
2 1 23456  
2 9 99999  
3 4 12345  
3 5 21234  
3 3 12456  
3 4 45632

结果将是

**ClID** **SeqNu** **Bal**  
1 1 30000  
2 9 99999  
3 4 45632
4

5 回答 5

4
select t.*
from (
    select CIID,
        MAX(Bal) as MaxBalance
    from table
    group by CIID
    ) sm
inner join table t on sm.CIID = t.CIID and sm.MaxBalance = t.Bal

SQL Fiddle 示例在这里

于 2012-04-25T13:49:58.170 回答
2

实现这一点的最佳方法可能会因您使用的 RDBMS 而异。如果您有窗口函数(例如,Oracle 9i+ 或 SQL Server 2012),以下应该可以工作:

select distinct ClId, 
                first_value(SeqNu) 
                    over (partition by ClId 
                          order by Bal desc) as SeqNu, 
                max(Bal) 
                    over (partition by ClId) as Bal
from your_table
于 2012-04-25T13:54:08.643 回答
1

您需要使用GROUP BY

SELECT SeqNu, MAX(Bal)
FROM Table
GROUP BY SeqNu
于 2012-04-25T13:47:24.447 回答
0

你需要做两个嵌套MAX语句来匹配它:

SELECT a.ClID, MAX(b.SeqNu) as SeqNu, b.Balance
FROM Table a
JOIN (SELECT ClID, MAX(Balance) as Balance FROM Table GROUP BY ClID) b 
   ON a.ClID = b.ClID AND a.Balance = b.Balance 
GROUP BY a.ClID, b.SeqNu
于 2012-04-25T13:49:29.387 回答
0
SELECT b1.*
FROM balance b1
LEFT JOIN balance b2
ON (b1.clid = b2.clid AND b2.bal > b1.bal)
WHERE b2.clid IS NULL;

+------+-------+-------+
| clid | seqnu | bal   |
+------+-------+-------+
|    1 |     1 | 30000 |
|    2 |     9 | 99999 |
|    3 |     4 | 45632 |
+------+-------+-------+
3 rows in set (0.00 sec)
于 2012-04-25T19:10:52.647 回答