如何按日期过滤列

时间:2012-06-11 05:33:33

标签: sql sql-server sql-server-2000

使用SQL Server 2000

表1

Id    date 
---   ----------
001   23/01/2012
002   25/01/2012
003 
004   01/02/2012

table1开始,我想显示id,日期为空或日期等于当月。

条件

  • 例如当前月份为02/2012表示我想显示ID 003和004,因为003日期为空,004日期等于当前月份日期...

    < / LI>
  • 如果当前月份为03/2012,则不应显示004日期

如何在SQL Server中执行此操作?

预期产出

Id     date 
003 
004    01/02/2012

5 个答案:

答案 0 :(得分:2)

使查询具有可搜索性非常重要,以便可以使用日期列上的索引。因此,形式函数(日期)(其中函数是年,月或日期部分)的where子句是错误的,因为SQL Server不能在日期使用索引。

相反,您希望对查询进行框架设置,使其形式为

select *
from table1
where (date is null) or (date between [STARTOFMONTH] and [ENDOFMONTH])

DateTime列,顾名思义,是一个TIME组件。因此,介于两者之间是非常棘手的,因为你想要直到月底的午夜,但不是午夜导致下个月...有些人试图通过从月底减去3毫秒来解决这个问题。这很糟糕,而不是未来的证明。

最好让查询看起来像

select *
from table1
where (date is null) or ( (date >= [STARTOFMONTH] and date < [STARTOFNEXTMONTH]) )

如何获取这些值(并与SQL 2000兼容......)? 一种方式,在我的头顶,是

cast(  floor( cast(dateAdd(d, -1 * day(getDate()) + 1, getDate()) as float ) ) as datetime )

并且通过向其添加一个月来获得下个月的开始。这将获取当前日期,减去当前月份中经过的天数,然后再添加1.然后我们的日期/时间等于该月的第一天,但​​仍然包含时间组件。一个转换为浮动,地板,然后再回到日期时间修复。

这可以放入标量或内联表UDF中,但为了简洁起见(已经有很长的答案!),你的where子句是

select *
from table1
where 
(date is null)
OR
(
  ( date >= cast(  floor( cast(dateAdd(d, -1 * day(getDate()) + 1, getDate()) as float ) ) as datetime ) )
  AND
  ( date < dateAdd(d, 1, cast(  floor( cast(dateAdd(d, -1 * day(getDate()) + 1, getDate()) as float ) ) as datetime ) ) )
)

希望有所帮助!

答案 1 :(得分:0)

Select * 
from table1 
where date is null or datepart(mm,getdate()) = datepart(mm,date)

答案 2 :(得分:0)

SELECT * FROM Table1 
WHERE (1=1)
AND
(
    MONTH(CURRENT_TIMESTAMP) = MONTH([date])
    AND
    YEAR(CURRENT_TIMESTAMP) = YEAR([date])
)
OR
(
    [date] IS NULL
)

答案 3 :(得分:0)

您可以使用为空年,月功能进行检查

select  Id
from Table1 
where date is null or (YEAR(GETDATE()) == Year(date) and Month(GETDATE()) == Month(date))

答案 4 :(得分:0)

尝试这种方式: -

SELECT *
FROM table1
WHERE date IS NULL OR (Year(currentDate) = Year(date) AND Month(currentDate) = Month(date))