Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Using SQL Last in an Aggregate Query


Using SQL Last in an Aggregate Query

Author
Message
garyh2k3
garyh2k3
Grasshopper
Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)Grasshopper (10 reputation)

Group: General Forum Members
Points: 10 Visits: 127
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.
Attachments
SQL Example.txt (7 views, 1.00 KB)
Robert klimes
Robert klimes
SSCommitted
SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)

Group: General Forum Members
Points: 1847 Visits: 3408
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
Jack Corbett
  Jack Corbett
SSChampion
SSChampion (11K reputation)SSChampion (11K reputation)SSChampion (11K reputation)SSChampion (11K reputation)SSChampion (11K reputation)SSChampion (11K reputation)SSChampion (11K reputation)SSChampion (11K reputation)

Group: General Forum Members
Points: 11020 Visits: 14858
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
At best you can say that one job may be more secure than another, but total job security is an illusion. -- Rod at work

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
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search