SQL获取列表中的值的MAX()值

时间:2018-12-21 17:14:41

标签: sql mysql-workbench

我有一个客户之间的交易数据库,可以这样描述:

Transaction ID  Sender  Receiver    Sender  Receiver Receipt
1   A   B   2   4
2   C   A   5   1
3   B   C   5   1
4   C   B   3   4

数据库按事务ID升序排序;如何获得每个客户的最后一个收据编号(发送者或接收者)

例如 A:1(A的最后一次出现在第2行中作为发件人) B:4(B的最后一次出现是在第4行中作为接收方) C:3(作为发送者,C的最后一次出现在第4行中)

谢谢

3 个答案:

答案 0 :(得分:0)

我正在猜测列名称,因为在您的问题中不清楚。
首先创建一个由3列TransactionID,名称,收据组成的查询。这将返回原始表中的行的两倍:发送方和收据分别为1行,接收方和收据为1行。
从此结果中,仅获取每个名称(探测器或接收者)具有最大id的行:

WITH t AS(
  SELECT TransactionID, Sender AS name, SenderReceipt AS receipt FROM transactions
  UNION
  SELECT TransactionID, Receiver AS name, ReceiverReceipt AS receipt FROM transactions
) 
SELECT 
  name, 
  receipt 
FROM t
WHERE 
  t.TransactionID = (
    SELECT MAX(TransactionID) 
    FROM t AS tt
    WHERE tt.name = t.name);

答案 1 :(得分:0)

获取用户作为发送者参与的最后一笔交易,对于接收者也是如此。合并结果并绘制用户参与任何角色的最后一笔交易。加入交易并根据用户在交易中的角色使用CASE输出收据。

SELECT `Last Transaction`.`Sender or Receiver`,
       CASE `Last Transaction`.`Sender or Receiver`
         WHEN `elbat`.`Sender` THEN
           `elbat`.`Sender Receipt`
         WHEN `elbat`.`Receiver` THEN
           `elbat`.`Receiver Receipt`
       END `Last Receipt`
       FROM (SELECT max(`Transaction ID`) `Transaction ID`,
                    `Sender or Receiver`
                    FROM (SELECT max(`Transaction ID`) `Transaction ID`,
                                 `Sender` `Sender or Receiver`
                                 FROM `elbat`
                                 GROUP BY `Sender`
                          UNION ALL
                          SELECT max(`Transaction ID`) `Transaction ID`,
                                 `Receiver` `Sender or Receiver`
                                 FROM `elbat`
                                 GROUP BY `Receiver`) `Last Transaction`
                    GROUP BY `Sender or Receiver`) `Last Transaction`
            INNER JOIN `elbat`
                       ON `elbat`.`Transaction ID` = `Last Transaction`.`Transaction ID`;

db<>fiddle

答案 2 :(得分:0)

如果有客户表,则可以执行以下操作:

select c.*,
       (select max(t.transactionid)
        from t
        where c.customerId in (t.sender, t.receiver)
       ) as last_transactionid
from customers c;

这可能具有不良的性能特征。使用正确的索引,此版本可能会更好:

select c.*,
       greatest( (select max(t.transactionid)
                  from t
                  where c.customerId = t.sender
                 ),
                 (select max(t.transactionid)
                  from t
                  where c.customerId = t.receiver
                 )
               ) as last_transactionid
from customers c;