我们有“交易”表:
long long digitsum(long long n) { // I assume n is non-negative
if (n == 0) return 0; // terminal case
return n % 10 + digitsum(n / 10);
}
我们需要获取每个交易ID(txn_id)具有最高状态的行。我们正在使用以下查询:
id amount txn_id status status_text
1 15 123456 0 pending
2 11 123123 0 pending
3 15 123456 1 complete
4 20 321456 0 pending
5 17 987456 0 pending
6 25 321321 0 pending
7 20 321456 1 complete
8 25 321321 1 complete
我们期望:
SELECT id, amount, txn_id, status, status_text, MAX(status) as max_status
FROM transactions
GROUP BY txn_id
ORDER BY id DESC
但是,除了“ status_text”和“ status”列(它们似乎是随机的)之外,我们一切都很好。 “ max_status”是正确的。
id amount txn_id status status_text max_status
8 25 321321 1 complete 1
7 20 321456 1 complete 1
5 17 987456 0 pending 0
3 15 123456 1 complete 1
2 11 123123 0 pending 0
我的想法不多了。 如何获得每个交易ID的状态最高的行?
谢谢!
答案 0 :(得分:0)
您可以在下面使用子查询尝试
select a.id,a.amount,a.txn_id, a.`status`, status_text,mstatus from transaction a
inner join
(
select txn_id,max(`status`) as mstatus
from transaction group by txn_id
)b on a.txn_id=b.txn_id and a.`status`=b.mstatus