Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Using SQL Last in an Aggregate Query Expand / Collapse
Author
Message
Posted Wednesday, August 21, 2013 12:28 PM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Monday, September 15, 2014 11:32 AM
Points: 10, Visits: 76
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.

  Post Attachments 
SQL Example.txt (7 views, 1.18 KB)
Post #1486852
Posted Wednesday, August 21, 2013 1:12 PM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Today @ 11:56 AM
Points: 1,407, Visits: 2,641
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
Post #1486886
Posted Thursday, August 22, 2013 7:31 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Today @ 3:23 PM
Points: 10,214, Visits: 13,161
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





Jack Corbett

Applications Developer

Don't let the good be the enemy of the best. -- Paul Fleming

Check out these links on how to get faster and more accurate answers:
Forum Etiquette: How to post data/code on a forum to get the best help
Need an Answer? Actually, No ... You Need a Question
How to Post Performance Problems
Crosstabs and Pivots or How to turn rows into columns Part 1
Crosstabs and Pivots or How to turn rows into columns Part 2
Post #1487252
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse