Log in  ::  Register  ::  Not logged in

## Set Up Grouping Intervals for Excel (SQL Spackle)

 Author Message dwain.c SSC Guru Group: General Forum Members Points: 70479 Visits: 6431 Comments posted to this topic are about the item Set Up Grouping Intervals for Excel (SQL Spackle) My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables steven.elliottjr SSC Rookie Group: General Forum Members Points: 35 Visits: 7 Wow, this is a great article and something that I've wondered about. Thanks! dwain.c SSC Guru Group: General Forum Members Points: 70479 Visits: 6431 steven.elliottjr (7/31/2012)Wow, this is a great article and something that I've wondered about. Thanks!Steven - Glad you found it helpful.Alas, when I looked at the published article, I found that my final edits to it were not included (probably my fault somehow). I had intended to jazz up the last example. So I'll post that now.Charting Over Date Periods (Continuous Data)Handling dates isn’t much different than the above but it does combine some of the features of both. We’ll define 30 intervals this time (2 days per interval). The main difference from FLOAT is there’s no need to fudge the endpoint (we’ll want it to be less than the end date of the final interval) and that the CASTs are to DATETIME, with CONVERT used to get the date into a format we like for the labels (mm/dd/yyyy).We’ll make this example more interesting by summing our Revenue and Expenses columns and adding a computed margin column.`-- Revised test harnessDECLARE @NumberOfRows INT ,@FStartValue FLOAT ,@FEndValue FLOAT ,@FRange FLOAT ,@IStartValue INT ,@IEndValue INT ,@IRange INT ,@DStartValue DATETIME ,@DEndValue DATETIME ,@DRange INT SELECT @NumberOfRows = 10000 -- Random FLOATs on the closed interval {275, 850} ,@FStartValue = 275 ,@FEndValue = 850 ,@FRange = @FEndValue - @FStartValue -- Random INTs starting at 41 and ending at 160 ,@IStartValue = 41 ,@IEndValue = 160 ,@IRange = @IEndValue - @IStartValue + 1 -- Example: The 30 day interval ending before midnight today --,@DStartValue = DATEADD(day, -30, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) --,@DEndValue = DATEADD(day, 30, DATEADD(day, -30, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))) -- -- The 60 day interval ending before midnight today ,@DStartValue = DATEADD(day, -60, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) ,@DEndValue = DATEADD(day, 60, @DStartValue) ,@DRange = DATEDIFF(day, @DStartValue, @DEndValue)DECLARE @MyTestTable TABLE (RandomInteger INT, RandomFloat FLOAT, RandomDate DATETIME, Revenue INT, Expenses INT)INSERT INTO @MyTestTableSELECT TOP (@NumberOfRows) RandomInteger = ABS(CHECKSUM(NEWID())) % @IRange + @IStartValue ,RandomFloat = RAND(CHECKSUM(NEWID())) * @FRange + @FStartValue ,RandomDate = RAND(CHECKSUM(NEWID())) * @DRange + @DStartValue -- Revenue and Expenses will be used in the final example ,Revenue = ABS(CHECKSUM(NEWID())) % 75 + 50 ,Expenses = ABS(CHECKSUM(NEWID())) % 45 + 25FROM sys.all_columns a1 CROSS JOIN sys.all_columns a2``-- Code for grouping intervals on revenue and marginDECLARE @NoIntervals INT = 30;WITH SetUpIntervals AS ( -- Anchor: Initial, placeholder interval for totals SELECT ID=0 ,StartInterval = CAST(NULL AS DATETIME) ,EndInterval = CAST(NULL AS DATETIME) ,Interval = CAST('Total' AS VARCHAR(40)) UNION ALL -- Anchor: Start interval taken from @DStartValue SELECT ID=1 ,StartInterval = @DStartValue ,EndInterval = 1 + (@DStartValue - 1) + @DRange/@NoIntervals ,Interval=CAST(CONVERT(VARCHAR(10), @DStartValue,101) + ' - ' + CONVERT(VARCHAR(10), (@DStartValue - 1) + @DRange/@NoIntervals, 101) AS VARCHAR(40)) UNION ALL -- Recursive: Next interval starts at last EndInterval SELECT ID + 1 ,EndInterval ,EndInterval + @DRange/@NoIntervals ,CAST(CONVERT(VARCHAR(10), EndInterval, 101) + ' - ' + CONVERT(VARCHAR(10), EndInterval + @DRange/@NoIntervals - 1, 101) AS VARCHAR(40)) FROM SetUpIntervals WHERE ID > 0 AND ID < @NoIntervals)--SELECT * FROM SetupIntervalsSELECT c.Interval ,Margin = CASE WHEN Margin IS NULL THEN 0 ELSE Margin END ,Expenses = CASE WHEN Expenses IS NULL THEN 0 ELSE Expenses END ,Revenue = CASE WHEN Revenue IS NULL THEN 0 ELSE Revenue ENDFROM SetupIntervals cLEFT JOIN ( -- Calculate Revenue, Expenses and Margin instead of COUNTing by RandomDate by Intervals SELECT ID, Margin=SUM(Revenue - Expenses), Revenue=SUM(Revenue), Expenses=SUM(Expenses) FROM @MyTestTable -- CROSS APPLY to put RandomDate into Intervals CROSS APPLY ( SELECT ID FROM SetUpIntervals WHERE RandomDate >= StartInterval AND RandomDate < EndInterval) a -- Use ROLLUP to get a total row in the grouped results set GROUP BY ID WITH ROLLUP) b ON ISNULL(b.ID, 0) = c.ID ORDER BY c.ID`For this case, it is instructive to examine the intervals created by SetUpIntervals. Examining the first and last few records (below), we see that our StartIntervals all align with our Interval labels, however the EndInterval is actually the next day at midnight.`ID StartInterval EndInterval Interval0 NULL NULL Total1 2012-04-08 00:00:00.000 2012-04-10 00:00:00.000 04/08/2012 - 04/09/20122 2012-04-10 00:00:00.000 2012-04-12 00:00:00.000 04/10/2012 - 04/11/20123 2012-04-12 00:00:00.000 2012-04-14 00:00:00.000 04/12/2012 - 04/13/201228 2012-06-01 00:00:00.000 2012-06-03 00:00:00.000 06/01/2012 - 06/02/201229 2012-06-03 00:00:00.000 2012-06-05 00:00:00.000 06/03/2012 - 06/04/201230 2012-06-05 00:00:00.000 2012-06-07 00:00:00.000 06/05/2012 - 06/06/2012`Once again, pasting our results into Excel we have a nicely formatted histogram over the desired date range. My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables Misha_SQL SSCarpal Tunnel Group: General Forum Members Points: 4123 Visits: 1099 Thank you for the article! Sorry if this is a silly question, but could somebody explain to me what is that little "x" doing on this line: CROSS APPLY (SELECT EndInterval + @IRange/@NoIntervals) x(EndInt) dwain.c SSC Guru Group: General Forum Members Points: 70479 Visits: 6431 mishaluba (8/2/2012)Thank you for the article! Sorry if this is a silly question, but could somebody explain to me what is that little "x" doing on this line: CROSS APPLY (SELECT EndInterval + @IRange/@NoIntervals) x(EndInt)You're welcome (for the article). :-)x is the table alias for (SELECT EndInterval + @IRange/@NoIntervals). EndInt is the alias for the computed field created in that derived table (EndInterval + @IRange/@NoIntervals). My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables Misha_SQL SSCarpal Tunnel Group: General Forum Members Points: 4123 Visits: 1099 A-a-a-a-ah! Thank you again!

## 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
 SQL Server 2017      SQL Server 2017 - Administration      SQL Server 2017 - Development SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 15 - Administration      SQL Server 15 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions      CosmosDB      Azure Data Lake      Azure Machine Learning Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization      Security and Auditing SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      Question of the Day (QOD)      SQL Server Security Skills Microsoft Access      Microsoft Access Products and Books      Third Party Products         CA         SQLCentric         Extreme Technologies.         Innovartis         Embarcadero         Sonasoft         Golden Gate Software         Idera         Lumigent         Red Gate Software         Quest Software         ApexSQL         SQL Sentry      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books         Discuss Data Warehousing Books  Notification Services      Administration Article Discussions Future Versions      SQL 12