问题
Possible Duplicate:
Selecting the Highest Seq Number by nested Joining
Hello I have to write a query , I would like to take biggest sequence number for each client Id (big sequence number will be calculated based on highest bank account balance).
Please consider this table has 100000records.
table is like as below-
Table:
**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
Result would be
**ClID** **SeqNu** **Bal** 1 1 30000 2 9 99999 3 4 45632
回答1:
The best way to accomplish this will probably vary depending on which RDBMS you're using. If you have windowing functions (Oracle 9i+ or SQL Server 2012, for instance), the following should work:
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
回答2:
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 example here
回答3:
You need to use a GROUP BY:
SELECT SeqNu, MAX(Bal)
FROM Table
GROUP BY SeqNu
回答4:
You need to do two nested MAX statements to match it all up:
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
回答5:
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)
来源:https://stackoverflow.com/questions/10317027/sql-table-highest-sequence-number