Selecting maximum distinct date by month

  • Hi Guys,

    I need to select a maximum distinct date by month. I have table, then I run the following query on it:

    select distinct yyyymmdd

    from view_MT

    order by yyyymmdd asc

    and I get:

    20090112

    20090130

    20090201

    20090215

    20090308

    Now I need to extract the maximum date by month from this list, so the output should be:

    20090130

    20090215

    20090308

    How would I achieve something like that? Thank you all for your time in advance.

  • I'm not promising that this will scale, but it will give the results you require

    DECLARE @table TABLE (date DATETIME)

    INSERT INTO @table (

    date

    )

    SELECT

    '20090112'

    UNION ALL

    SELECT

    '20090130'

    UNION ALL

    SELECT

    '20090201'

    UNION ALL

    SELECT

    '20090215'

    UNION ALL

    SELECT

    '20090308'

    SELECT

    MAX(date)

    FROM

    @table

    GROUP BY

    DATEPART(MONTH, date)

    Please note how I provide test data.

  • Jack, thank you so much for your help, that worked wonderful!

    Thanks again,

    Mikhail

  • Jack Corbett (6/2/2009)


    I'm not promising that this will scale, but it will give the results you require

    DECLARE @table TABLE (date DATETIME)

    INSERT INTO @table (

    date

    )

    SELECT

    '20090112'

    UNION ALL

    SELECT

    '20090130'

    UNION ALL

    SELECT

    '20090201'

    UNION ALL

    SELECT

    '20090215'

    UNION ALL

    SELECT

    '20090308'

    SELECT

    MAX(date)

    FROM

    @table

    GROUP BY

    DATEPART(MONTH, date)

    Please note how I provide test data.

    Your query might return incorrect results if the dates are from multiple years. The following query gets around that by grouping by the first day of the month.

    SELECT

    MAX(date)

    FROM

    @table

    GROUP BY

    dateadd(month,datediff(month,0,date),0)

  • Thanks Michael.

    That is a better solution. I did too quick a solution.

  • Thanks again guys, everything is working 🙂

  • To be very safe, remember to group by year and month, not just by month. Otherwise you will run into problems if your data spans more than one year.

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply