【问题标题】:error with comparing dates to find out max(date) in mysql比较日期以找出 mysql 中的 max(date) 时出错
【发布时间】:2016-09-06 22:52:38
【问题描述】:

我有这个问题:

查找每个帐户,他的最后一笔交易,4 月,所有 使用美元的帐户。结果应键入:a) 帐户的 代码 b) 最后一笔交易的代码(如果一天有两笔交易,您应该在 最新交易) c) 上次交易的日期。

我的问题是:如何比较一个帐户的所有日期?

    SELECT DISTINCT 
         accounts.account_id
         ,transactions.trn_code 
         ,transactions.trn_date
    FROM accounts 
         inner join transactions on accounts.account_id = transactions.account_id
    WHERE 
         accounts.account_currency = 'DOL' 
         and  transactions.trn_date = MAX(transactions.trn_date)
         and transactions.trn_date >= 01/04/2016 and transactions.trn_date <= 31/4/2016

这会导致错误(当然),因为我不能那样使用 MAX。但我想我必须找到每个帐户本月的最大交易日期。这个想法对吗? 我怎样才能做到这一点?有什么想法吗?

【问题讨论】:

    标签: mysql sql date transactions mysql-workbench


    【解决方案1】:

    你好,你可以试试这个

     SELECT accounts.account_id, transactions.trn_code , transactions.trn_date
        FROM accounts inner join transactions on accounts.account_id = transactions.account_id
        WHERE accounts.account_currency = 'DOL'   
    and transactions.trn_date >= 01/04/2016 and transactions.trn_date <= 31/4/2016 and transactions.trn_date=(Select MAX(transactions.trn_date) from transactions)
    group by transactions.trn_code , transactions.trn_date,accounts.account_id
    

    【讨论】:

    • 谢谢!它现在执行,但我没有得到我想要的结果:/如果一个帐户的交易多于一个(2016 年 1 月 4 日至 2016 年 4 月 31 日之间),结果会给我这个帐户的所有交易(每个都有他的日期)。但我只想要帐户最近日期的交易。
    猜你喜欢
    • 1970-01-01
    • 2019-09-21
    • 2013-06-23
    • 1970-01-01
    • 2017-12-04
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    相关资源
    最近更新 更多