【问题标题】:MySQL getting records between specific month, yearMySQL获取特定月份,年份之间的记录
【发布时间】:2017-08-08 11:17:31
【问题描述】:

我有一个名为 Accounts 的表,其中有一个名为 TransactionDate 的日期列。我需要获取 TransactionDate 介于月、年之间的所有记录。

例如,TransactionDate 介于 2016 年 6 月和 2017 年 8 月之间的所有记录。

我的查询字符串如下所示:

SELECT Amount 
  FROM Accounts 
 WHERE (MONTH(TransactionDate) BETWEEN 6 and 8) 
   AND (YEAR(TransactionDate) BETWEEN 2016 and 2017)  
 ORDER BY TransactionDate ASC

但是它只给了我 2016 年 6 月、7 月和 2017 年 8 月的记录。它跳过了 2017 年 1 月、2016 年 11 月 Spet 的记录。

我附上所有记录的TransactionDate列的截图(共有31条)

这是返回结果的截图

我的查询有什么问题?此外,此查询将是动态的,即用户将从表单中选择月份和年份,并将结果返回给他们。

谢谢。

【问题讨论】:

  • 该输出基于您显示的输入和您运行的查询看起来正确

标签: mysql database between


【解决方案1】:

您只需按 2017 年 8 月之前和 2016 年 6 月之后的查询过滤查询

SELECT Amount 
  FROM Accounts 
 WHERE TransactionDate > '2016-06-01T00:00:00' 
   AND TransactionDate < '2017-08-01T00:00:00' 
 ORDER BY TransactionDate ASC

您当前查询的问题在于,您获取的数据月份为 6 月、7 月或 8 月,年份为 2016 或 2017 年。这是不对的,您想按日期本身进行过滤,而不是组件。

【讨论】:

    【解决方案2】:

    你似乎想要:

    select a.Amount
    from Accounts a
    where a.TransactionDate >= '2016-06-01' AND
          a.TransactionDate < '2017-09-01'
    order by a.TransactionDate ASC
    

    【讨论】:

      【解决方案3】:
      select Amount from Accounts where TransactionDate  BETWEEN '2016-04-02' AND '2017-08-03';
      

      试试这个,祝你好运

      【讨论】:

        【解决方案4】:

        我认为这是你需要的

        SELECT Amount , ExpenseType , 
              MONTHNAME(TransactionDate) AS TransactionMonthString
              Year(TransactionDate) AS TransactionYearString
        FROM Accounts 
        WHERE TransactionDate >= '2016-06-01' AND TransactionDate <= '2017-08-01'   
        ORDER BY TransactionDate
        

        【讨论】:

          【解决方案5】:

          你可以使用mysql的date_format函数轻松做到这一点

           SELECT 
               Amount
           FROM
               Accounts
           WHERE
               DATE_FORMAT(TransactionDate, '%Y-%m') BETWEEN '2016-06' AND '2017-08' ORDER BY TransactionDate ASC;
          

          这应该可以完美运行。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多