我想从行中获取卡号的剩余/最新余额。以下是该表的样本。
trans_id | cardnumber | trans_date | balance
---------------------------------------------------------------
1 | 1000005240000008 | 2009-07-03 04:54:27 | 88
2 | 1000005120000008 | 2009-07-04 05:00:07 | 2
3 | 1000005110000008 | 2009-07-05 13:18:39 | 3
4 | 1000005110000008 | 2009-07-06 13:18:39 | 4
5 | 1000005110000008 | 2009-07-07 14:25:32 | 4.5
6 | 1000005120000002 | 2009-07-08 16:50:51 | -1
7 | 1000005240000002 | 2009-07-09 17:03:17 | 1
结果应如下所示:
trans_id | cardnumber | trans_date | balance
---------------------------------------------------------------
1 | 1000005110000008 | 2009-07-07 14:25:32 | 4.5
2 | 1000005120000002 | 2009-07-08 16:50:51 | -1
3 | 1000005240000002 | 2009-07-09 17:03:17 | 1
我已经有了一个查询,但它是这样的:
SELECT cardnumber, MAX(balance), trans_date
FROM transactions
GROUP BY cardnumber
我真的需要帮助,我很难过。 :( 提前谢谢。
标记
答案 0 :(得分:2)
我现在面前没有MySQL,但是这样的事情应该有效:
SELECT latest.cardnumber, latest.max_trans_date, t2.balance
FROM
(
SELECT t1.cardnumber, MAX(t1.trans_date) AS max_trans_date
FROM transactions t1
GROUP BY t1.cardnumber
) latest
JOIN transactions t2 ON (
latest.cardnumber = t2.cardnumber AND
latest.max_trans_date = t2.trans_date
)
可能需要5.0.x或更高版本。可能有更好的方法。现在是凌晨3点:-D
答案 1 :(得分:0)
几乎和德罗伯特一样,但其他方面。无论如何,您的想法是创建一个子查询,该子查询使用最新(最大)事务日期的卡号,然后将其与原始表连接。当然,这假设在同一时间卡号上没有任何交易。
SELECT t1.trans_id, t1.cardnumber, t1.trans_date, t1.balance
FROM transaction AS t1
JOIN (SELECT MAX(trans_date), cardnumber FROM transactions) AS t2 ON t2.cardnumber = t1.cardnumber
答案 2 :(得分:0)
SELECT * FROM Transactions WHERE(cardnumber,trans_date)in(SELECT cardnumber,MAX(trans_date)FROM transactions GROUP BY cardnumber);