Using SQL Last in an Aggregate Query

  • I have a query that uses the SUM aggregate function to return results for over 200 columns. Based on the @DateFrequency selected it groups the results by ('Daily', 'Weekly', 'Monthly') for a selected start and end date timeframe. The issue is now for several of the columns they want to just have the last record result for that timeframe. So if weekly or monthly is selected it will only display the last record available for that column by the most recent date. I know you can use the (select top 1... order by date desc) to get this result traditionally but the issue I am running into is the query uses all aggregates. So any calculation I make since it is not an aggregate it wants me to add that to the group by which then skews my results that right now group correctly based on the @DateFrequency selected. I tried creating a UDF that uses the TOP 1 logic but it still wants me to include the column name in the group by unless there is something I am doing incorrectly. Is it possible with the given conditions I have described to get a last record result or do I need to rework the query? I have attached a condensed version of my query. Any feedback would be appreciated.

  • it is tough to give you an answer without some DDL and sample data. read the link in my sig to get better help.

    that being said possibly something like this will get you started. its not pretty and probably wont scale well.

    CREATE TABLE #temp(datefreq CHAR(7), val INT,startdate DATETIME)

    INSERT INTO #temp(datefreq,val,startdate)

    VALUES('weekly',1,'2012-01-01'),

    ('weekly',5,'2012-07-07'),

    ('weekly',10,'2013-05-31'),

    ('monthly',2,'2013-08-08'),

    ('monthly',10,'2013-07-06'),

    ('monthly',25,'2013-01-01')

    SELECT datefreq,SUM(val),CASE WHEN datefreq = 'weekly' THEN (SELECT TOP 1 val FROM #temp WHERE datefreq='Weekly' ORDER BY startdate DESC)

    WHEN datefreq = 'monthly' THEN (SELECT TOP 1 val FROM #temp WHERE datefreq='monthly' ORDER BY startdate DESC) END

    FROM #temp

    GROUP BY datefreq

    DROP TABLE #temp

    Bob
    -----------------------------------------------------------------------------
    How to post to get the best help[/url]

  • I'm not sure that the query you provided is doing what you think, unless the Start Date and End Date passed in are based on the data frequency meaning when you pass in Weekly as DateFrequency the start date and end date passed in is one week.

    It definitely would be easier if you provided some sample data and the results you'd expect from the sample data.

    Based on the information we have I'd think something along the lines of making the summing query a CTE, then creating a 2nd CTE based on that data that adds a row_number() to determine which is the last value and then a final select that selects where rowNo = 1. Something like this:

    WITH summedData

    AS (

    SELECT

    @DateFrequency AS [Date],

    SUM(CONVERT(INT, [SATX Closed on First Contact (COFC) Footprints])) AS "SATX Closed on First Contact (COFC) Footprints",

    SUM(CONVERT(INT, [SATX Total New Tickets])) AS "SATX Total New Tickets",

    SUM(CONVERT(INT, [SATX Phone])) AS "SATX Phone",

    SUM(CONVERT(INT, [SATX Email])) AS "SATX Email",

    SUM(CONVERT(INT, [SATX Chat])) AS "SATX Chat",

    SUM(CONVERT(INT, [SATX Customer Portal])) AS "SATX Customer Portal",

    SUM(CONVERT(INT, [SATX New Tickets (H9)])) AS "SATX New Tickets (H9)",

    SUM(CONVERT(INT, [SATX New Tickets (Non-H9)])) AS "SATX New Tickets (Non-H9)",

    SUM(CONVERT(INT, [SATX Total Tickets Closed])) AS "SATX Total Tickets Closed",

    SUM(CONVERT(INT, [SATX Closed Tickets (H9)])) AS "SATX Closed Tickets (H9)",

    SUM(CONVERT(INT, [SATX Closed Tickets (Non-H9)])) AS "SATX Closed Tickets (Non-H9)",

    MIN(dbo.ufnSATXGetLastRecord([SATX Total Incident Tickets Outstanding])) AS "SATX Total Incident Tickets Outstanding",

    SUM(CONVERT(INT, [SATX Incident Tickets Outstanding (H9)])) AS "SATX Incident Tickets Outstanding (H9)"

    FROM

    SATXFPMetrics

    WHERE

    [Date] >= @StartDate AND

    [Date] <= @EndDate

    ),

    addRowNo

    AS (

    SELECT

    ROW_NUMBER() OVER (ORDER BY [Date] DESC) AS rowNo,

    *

    FROM

    summedData

    )

    SELECT

    *

    FROM

    addRowNo

    WHERE

    rowNo = 1

Viewing 3 posts - 1 through 2 (of 2 total)

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