SQL Filter Out Specific Month, Day, and Time for Any Year

混江龙づ霸主 提交于 2019-12-08 06:32:44

问题


Microsoft Dynamics NAV uses the datetime of yyyy-12-31 23:59:59.000 to identify yearly closing entries. I am trying to write a report that will bring all of my entries, except for these. The query works fine for 2014 if I explicitly use a WHERE clause of

WHERE [Posting Date] <> '2014-12-31 23:59:59.000')

But I need the query to work for any year. I tried:

WHERE (DATEPART(mm, [Posting Date]) <> 12) AND 
      (DATEPART(dd, [Posting Date]) <> 31) AND 
      (DATEPART(hh, [Posting Date]) <> 23) AND 
      (DATEPART(mi, [Posting Date]) <> 59) AND 
      (DATEPART(ss, [Posting Date]) <> 59)

But that filtered out everything that was in December or had a day of 31 or an hour of 23, etc...

Is there a simple way to filter a given datetime, but with any year?


回答1:


May be this:

WHERE MONTH([Posting Date]) <> 12 OR
      DAY([Posting Date]) <> 31 OR
      CAST([Posting Date] AS TIME) <> CAST('23:59:59.000' AS TIME)

Even more short answer:

WHERE YEAR([Posting Date]) <> YEAR(DATEADD(ss, 1, [Posting Date]))



回答2:


Another thing which you can also do is something like this, which is a slight variation from what you have tried.

WHERE 1 = CASE 
        WHEN (
                DATEPART(MONTH, [POSTING DATE]) = 12
                AND DATEPART(DAY, [POSTING DATE]) = 31
                AND DATEPART(HOUR, [POSTING DATE]) = 23
                AND DATEPART(MINUTE, [POSTING DATE]) = 59
                AND DATEPART(SECOND, [POSTING DATE]) = 59
                )
            THEN 0
        ELSE 1
        END

In this scenario I just use a CASE to identify those rows which have the date the last second of the year and the evaluation of 1/0 does the rest and filters out the unwanted records.



来源:https://stackoverflow.com/questions/30530869/sql-filter-out-specific-month-day-and-time-for-any-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!