gpt4 book ai didi

php - 获取使用 "group by"检索的正确行值

转载 作者:行者123 更新时间:2023-11-29 16:46:48 25 4
gpt4 key购买 nike

我们有“交易”表:

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

我们需要获取每个事务 ID (txn_id) 状态最高的行。我们正在使用这个查询:

SELECT id, amount, txn_id, status, status_text, MAX(status) as max_status 
FROM transactions
GROUP BY txn_id
ORDER BY id DESC

我们期待:

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

但是除了“status_text”和“status”列看起来是随机的之外,我们一切都正确。 “max_status”是正确的。

id  amount  txn_id  status  status_text  max_status
8 25 321321 1 complete 1
7 20 321456 0 pending 1
5 17 987456 0 pending 0
3 15 123456 0 complete 1
2 11 123123 0 pending 0

我的想法已经用完了。我们如何获取每个事务 ID 状态最高的行?

谢谢!

最佳答案

您可以尝试使用下面的子查询

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

关于php - 获取使用 "group by"检索的正确行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53046229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com