简体   繁体   中英

function to get date range for query

I have following code to pull data between first day of month and yesterdays date unless current day is the first of month in which case it will pull first of previous month and yesterdays date. Problem is code is not working all of the time, is not working this month. I'm thinking it's not working because it's taking the last day of may (may 31st) subtracting 1 month but there is no April 31st so it's going to may 1st? Here is the code.

Between Add_months(last_day(sysdate-1)-1)+1 and sysdate-1

Just need code that will always pull between 1st of month and yesterday unless current date is 1st then it will pull 1st of previous month and yesterdays date.

Your expression can even be simplified:

BETWEEN TRUNC(SYSDATE - 1, 'MM') AND SYSDATE - 1

TRUNC(date, 'MM') wil round downwards to the first of the month and set the time components to 0. It's probably even cleaner to clear the time components of yesterday as well. Without the second argument, TRUNC will round down to the start of the day:

BETWEEN TRUNC(SYSDATE - 1, 'MM') AND TRUNC(SYSDATE - 1)
;WITH rangeCTE AS
(
    SELECT  Convert(DateTime, '2013-09-01') minDate,
            Convert(DateTime, '2014-06-30') maxDate
)

,datelistCTE AS
(
        SELECT  CAST(CONVERT(CHAR(6),minDate,112) + '01' AS DATETIME) AS monthStart,
                DATEADD(mm, 1, CAST(CONVERT(CHAR(6), minDate, 112) + '01' AS DATETIME)) -1 AS monthEnd
               ,1 AS monthID
        FROM rangeCTE

        UNION ALL

        SELECT  DATEADD(mm, 1, monthStart)
               ,DATEADD(mm, 2, monthStart) - 1
               ,monthID + 1
        FROM datelistCTE
        WHERE monthStart <= (SELECT maxDate FROM rangeCTE)
)
select * from datelistCTE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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