【问题标题】:SQL query to get result for a date range when table got Year and Month fields当表获得年份和月份字段时,SQL查询以获取日期范围的结果
【发布时间】:2017-11-20 15:59:28
【问题描述】:

我有一个包含年份和月份字段的表格。我需要选择两个特定日期之间的行。如何在 where 条件下设置它?

【问题讨论】:

  • 编辑您的问题并提供示例数据、所需结果和您正在使用的数据库的标签。
  • 类似...where yearcol * 100 + monthcol between 201601 and 201612
  • 您使用的是哪个DBMS 产品?后格雷斯?甲骨文? “SQL”只是一种查询语言,并不是特定数据库产品的名称。
  • 我添加了一个样本数据集。我使用 SQL 服务器。
  • 是以数字形式存储的年份和日期(而不是字符串?)

标签: sql sql-server date where where-clause


【解决方案1】:

在这种情况下,您对“介于”的含义有点不清楚。我很确定datefromparts() 会很有帮助:

select t.*
from t
where @date_start <= datefromparts(year, month, 1) and
      @date_end >= datefromparts(year, month, 1);

如果月底是一个重要的日期,您可能还会发现 eomonth() 很有帮助。

【讨论】:

  • 不错 :) 但我认为它仅在 SQL Server 2012 及以后版本中可用
  • @Grantly 。 . .嗯,是的,而且该软件已经推出 5 年多了。
  • LOL 是的,这些天我真的落后了。刚刚提到它以防有人在使用该功能时遇到问题,比如我。我有很多版本在运行,但还没有到 2012,2014 (虽然我的一些客户是)
【解决方案2】:

你可以试试帮助month(),year()函数的日期

示例如下:

select * from t where (t.month=month('2017-01-01') and t.year=year('2017-01-01')) and (t.month=month('2017- 05-01') 和 t.year=year('2017-05-01'));

下面是sql中month()的链接。 https://docs.microsoft.com/en-us/sql/t-sql/functions/month-transact-sql

这可能会帮助您解决问题。

【讨论】:

  • 很确定问题需要两个日期之间的结果,不等于两个日期 - 看起来它无论如何都行不通......但是很好的尝试。也许你可以改进你的答案?
【解决方案3】:

你也可以试试:

select
  d.*
from
  (select
    t.*,
    cast(rtrim(cast([month] as char(2))) + '/1/' + cast ([year] as char(4)) as date) as dt) d
where
dt >= @dateStart and
dt <= @dateEnd

【讨论】:

    【解决方案4】:

    如果年份和月份值是整数,您可以将它们转换为 varchar,然后是日期,然后使用 BETWEEN。声明 startdate 和 enddate 变量的示例:

    DECLARE @startdate date = '2015-07-01'
           ,@enddate   date = '2016-07-01'
    
    SELECT *       
      FROM @myTable
    WHERE CAST(CAST(Year as varchar) + '-' + CAST(Month as varchar) + '-01' as date) 
          BETWEEN @startdate AND @enddate
    

    如果它们是 chars 或 varchars,您只需转换为 date 并使用 BETWEEN:

    DECLARE @startdate date = '2015-07-01'
           ,@enddate   date = '2016-07-01'
    
    SELECT *       
      FROM @myTable
    WHERE CAST(Year + '-' + Month + '-01' as date) 
          BETWEEN @startdate AND @enddate
    

    【讨论】:

      【解决方案5】:

      尝试使用“Between”。

      类似这样的:

      从 2015 年到 2016 年以及 6 到 8 月之间的表中选择 SALES_AMOUNT

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-11
        • 1970-01-01
        • 1970-01-01
        • 2016-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多