【问题标题】:Selecting records using year and month fields - SQL Server使用年份和月份字段选择记录 - SQL Server
【发布时间】:2018-10-12 15:24:37
【问题描述】:

我需要使用给定年份和月份的范围从表中选择记录不工作。

SELECT TOP 1000 [Clave Titular Cedula]
      ,[Clave Cifcod]
      ,[Clave Anio corte historico]
      ,[Clave Mes de corte historico]
      ,[Clave Tipo de tarjeta]
      ,[ClaveCodigo grupo inf#promocio]
      ,[Clave Codigo subgrupo inf#prom#]
      ,[Cant# Compras]
      ,[Valor Compras]
  FROM [Prueba].[dbo].[Gasto]
     where ([Clave Titular Cedula] = '0917947160' and [Clave Cifcod] = '284849' and [ClaveCodigo grupo inf#promocio] = '05')
and  (([Clave Anio corte historico] = '2016' and [Clave Mes de corte historico] >= 02)
     or ([Clave Anio corte historico]  > '2016' and [Clave Anio corte historico] < '2016')
     or ([Clave Anio corte historico] = '2016' and [Clave Mes de corte historico] <= 09) ) 

例如,这会返回从 01 月开始的记录,而不是从 02 月开始的记录。

任何建议将不胜感激。

提前致谢,

鲍里斯

【问题讨论】:

  • 您的最后一个 or 声明允许返回 2016 年小于 10 的所有月份 - 第 1 个月是其中的一部分。您需要重构您的查询。如果您正在寻找一个范围 - 尝试在几个月之间使用
  • 除了([Clave Anio corte historico] &gt; '2016' and [Clave Anio corte historico] &lt; '2016') 之外什么都没有——这在您的查询中有何意义?没有记录可以同时满足这两个标准 - 设置 Clave Anio Corte Historice = 2016 和 Clave Mes de corte historice BETWEEN 2 AND 9

标签: sql sql-server


【解决方案1】:

您的查询简化为:

SELECT TOP 1000 
    [Clave Titular Cedula]
    ,[Clave Cifcod]
    ,[Clave Anio corte historico]
    ,[Clave Mes de corte historico]
    ,[Clave Tipo de tarjeta]
    ,[ClaveCodigo grupo inf#promocio]
    ,[Clave Codigo subgrupo inf#prom#]
    ,[Cant# Compras]
    ,[Valor Compras]
FROM 
    [Prueba].[dbo].[Gasto]
where 
    ( [Clave Titular Cedula] = '0917947160' )
    and ( [Clave Cifcod] = '284849' )
    and ( [ClaveCodigo grupo inf#promocio] = '05')
    and ( [Clave Anio corte historico] = '2016' ) 
    and ( [Clave Mes de corte historico] between 02 and 09 )

【讨论】:

    【解决方案2】:

    您可以通过排除所有错误选项来使用它。我更喜欢你把年份和月份结合起来,比如:yyyy-mm

    SELECT * FROM tables WHERE NOT (From_date < #RangeEnd OR To_date > #RangeStart)
    

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      相关资源
      最近更新 更多