简体   繁体   中英

SQL - date range from current date to 2 years ago

I'm new here and kind of a noob to sql as well. I need help on this logic. The issue is in the "dateadd" function I believe. I need to get the date range of the current date (August 2014) to 2 years ago (August 2012). One of my mates said I could use a max function but he is not sure how to either. Not sure what to do..please guide me. Thanks!

--count of EDI exceptions daily with current status
select count(InvoiceUniqueness) as [Nbr], CONVERT(varchar(12), ProcessDate, 101) as            [Date],
case currentstatus when 1 then 'production' when 2 then 'exception' when 3 then 'archive'     end as [CurrentStatus]
from PreProcessTransLog
where (CONVERT(DATETIME, ProcessDate, 102)) >= dateadd (yy,-2,getdate()) and  InitialStatus  =2
group by CONVERT(varchar(12), ProcessDate, 101), currentstatus
order by CAST (CONVERT(varchar(12), ProcessDate, 101) as smalldatetime) desc

Results from the Query:

    6   10/11/2014  production
    12  10/10/2014  production
    3   09/30/2014  production
    2   09/28/2014  production
    34  09/27/2014  production
    39  09/26/2014  production
    150 08/02/2014  exception
    40  08/01/2014  production
    62  08/01/2014  archive
    437 08/01/2014  exception
    60  07/31/2014  production
    54  07/31/2014  archive
    46  07/31/2014  exception
    61  07/30/2014  exception
    113 07/30/2014  production
    98  07/30/2014  archive
    7   07/29/2014  exception
    130 07/29/2014  archive
    80  07/29/2014  production
    84  07/28/2014  production
    ....
    ....
    ....

As you can see I'm getting a dates after August like September and October. I just want to current date.

Thanks!!

Can you just add in ProcessDate <= today's date?

SELECT  COUNT(InvoiceUniqueness) AS [Nbr] ,
        CONVERT(VARCHAR(12), ProcessDate, 101) AS [Date] ,
        CASE currentstatus
          WHEN 1 THEN 'production'
          WHEN 2 THEN 'exception'
          WHEN 3 THEN 'archive'
        END AS [CurrentStatus]
FROM    PreProcessTransLog
WHERE    CONVERT(DATETIME, ProcessDate, 102)  >= DATEADD(yy, -2, GETDATE())
        AND ProcessDate <= GETDATE()
        AND InitialStatus = 2
GROUP BY CONVERT(VARCHAR(12), ProcessDate, 101) ,
        currentstatus
ORDER BY CAST (CONVERT(VARCHAR(12), ProcessDate, 101) AS SMALLDATETIME) DESC

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