使用“groupby”获取正确的行值

h4cxqtbf  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(391)

这个问题在这里已经有答案了

检索每个组中的最后一条记录-mysql(29个答案)
两年前关门了。
我们有“交易”表:

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

我们需要为每个事务id(txn\u id)获取状态最高的行。我们正在使用此查询:

  1. SELECT id, amount, txn_id, status, status_text, MAX(status) as max_status
  2. FROM transactions
  3. GROUP BY txn_id
  4. ORDER BY id DESC

我们期待:

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

但除了“状态文本”和“状态”列外,我们的一切都是正确的,这些列似乎是随机的。”“最大状态”正确。

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

我没什么主意了。如何获得每个事务id的状态最高的行?
谢谢您!

wxclj1h5

wxclj1h51#

您可以在下面使用子查询进行尝试

  1. select a.id,a.amount,a.txn_id, a.`status`, status_text,mstatus from transaction a
  2. inner join
  3. (
  4. select txn_id,max(`status`) as mstatus
  5. from transaction group by txn_id
  6. )b on a.txn_id=b.txn_id and a.`status`=b.mstatus

相关问题