繁体   English   中英

SQL 按月和年选择日期范围

[英]SQL select date range by month and year

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

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

我目前的查询:

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

我会使用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包容的第一个参数,并独家第二,所以我撞一天到23日。

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);
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');
    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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM