您好我必须写一个查询,我想为每个客户端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
答案 0 :(得分: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
答案 1 :(得分:2)
您需要使用GROUP BY
:
SELECT SeqNu, MAX(Bal)
FROM Table
GROUP BY SeqNu
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分: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)