【问题标题】:SQL select date range by month and yearSQL按月和年选择日期范围
【发布时间】:2018-12-24 22:30:22
【问题描述】:

如何从这个查询中选择日期范围?

例如:从 Month('2017-05-22') 和 Year(date1) = Year('2017-05-22') to Month('2018-05-22') 和 Year(date1) = Year('2018-05-22')

我当前的查询:

SELECT 
  date1
FROM 
  data
WHERE 
  Month(date1) = Month('2018-05-22') And Year(date1) = Year('2018-05-22')

【问题讨论】:

  • 分享您的样本数据和预期输出

标签: mysql sql


【解决方案1】:

我会使用 str_to_date 将这些文字转换为日期:

SELECT MONTH(date1)
FROM   data
WHERE  date1 BETWEEN STR_TO_DATE('2017-05-22', '%Y-%m-%d') AND STR_TO_DATE('2018-05-23', '%Y-%m-%d')

请注意,between 在第一个参数上是inclusive,在第二个参数上是exclusive,所以我将这一天推迟到了 23 日。

【讨论】:

  • 它可以工作,但我只需要一个月,例如当我通过 '2018-05-22' 时,它会在五月显示一整天或一个月。
  • @AmirulFahmi 您可以通过调用month 从结果中提取月份。请参阅我编辑的答案。
【解决方案2】:

BETWEEN 条件以检索日期范围内的值。

例如:

SELECT *
FROM order_details
WHERE order_date BETWEEN CAST('2014-02-01' AS DATE) AND CAST('2014-02-28' AS DATE);

这个 MySQL BETWEEN 条件示例将返回 order_details 表中 order_date 介于 2014 年 2 月 1 日和 2014 年 2 月 28 日(含)之间的所有记录。它相当于下面的 SELECT 语句:

SELECT *
FROM order_details
WHERE order_date >= CAST('2014-02-01' AS DATE)
AND order_date <= CAST('2014-02-28' AS DATE);

【讨论】:

  • thx ..但是当它像'2018-02-22'一样投射时我如何显示它会显示为二月等等
  • 日期范围选择和月份显示不同,您可以轻松地从任何日期值显示日、月或年 mysql 具有所有类型的函数 DAY('2008-05-15') 它将返回 15 , MONTH('2009-05-18') 它将返回 5
【解决方案3】:
SELECT TO_CHAR(systemts, 'yyyy-mm') as yyyymm,
       max(notenum) - min(notenum) + 1 as notenum_range
FROM your_table_name
WHERE systemts >= to_date('2018-01-01', 'yyyy-mm-dd') AND
      systemts < to_date('2018-07-17', 'yyyy-mm-dd')
GROUP BY TO_CHAR(systemts, 'yyyy-mm');

【讨论】:

  • 这仅适用于 oracle sql 吗?
【解决方案4】:
    DECLARE @monthfrom int=null,
    @yearfrom int=null,
    @monthto int=null,
    @yearto int=null

/**Region For Create Date on Behalf of Month & Year**/
    DECLARE @FromDate DATE=NULL
    DECLARE @ToDate DATE=NULL

    SET @FromDate=DateAdd(day,0, DateAdd(month, @monthfrom - 1,DateAdd(Year, @yearfrom-1900, 0)))
    SET @ToDate=DateAdd(day,-1, DateAdd(month, @monthto - 0,DateAdd(Year, @yearto-1900, 0)))
/**Region For Create Date on Behalf of Month & Year**/

SELECT DISTINCT month ,Year FROM  tbl_Att
WHERE  (DATEADD(yy, year - 1900, DATEADD(m, Month - 1, 1 - 1)) BETWEEN CONVERT(DATETIME, @FromDate, 102) AND 
CONVERT(DATETIME, @ToDate, 102))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多