Log in  ::  Register  ::  Not logged in

## Problem with writing a query. Kindly guide...

 Author Message dwain.c SSC-Forever Group: General Forum Members Points: 43905 Visits: 6431 Continuing curiosity regarding this problem drove me to see how the proposed solutions scale, so I built a test harness.`CREATE TABLE #T (Rate int NOT NULL,Shift int NOT NULL,PRIMARY KEY (Rate, Shift));INSERT INTO #T ( Rate, Shift )VALUES (-1, 1), (-1, 2), (-1, 3);WITH Tally (n) AS( SELECT TOP 500000 ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM sys.all_columns a CROSS JOIN sys.all_columns b),STally (n) AS( SELECT TOP 10 ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM sys.all_columns a )INSERT INTO #TSELECT a.n, b.n FROM Tally aCROSS APPLY STally b;DELETE FROM #TWHERE (Rate < 20000 AND Shift = 1) OR (Rate > 400000 AND Shift = 3) OR (RATE BETWEEN 50000 AND 150000 AND Shift = 2);DECLARE @Rate INT = -1 ,@Holder INT ,@StartDT DATETIME;SELECT @StartDT=GETDATE();PRINT 'Solution by Hunchback';SET STATISTICS TIME ON;WITH C1 AS (SELECT ShiftFROM #TWHERE Rate = @Rate)SELECT @Holder=A.RateFROM #T AS A INNER JOIN C1 AS B ON A.Shift = B.ShiftGROUP BY A.RateHAVING COUNT(*) = (SELECT COUNT(*) FROM C1);SET STATISTICS TIME OFF;SELECT ElapsedMS=DATEDIFF(millisecond, @StartDT, GETDATE());SELECT @StartDT=GETDATE();PRINT 'Solution by Dwain.C';SET STATISTICS TIME ON;SELECT @Holder=RateFROM #TWHERE Shift IN (SELECT Shift FROM #T WHERE Rate = @Rate)GROUP BY RateHAVING COUNT(*) = (SELECT COUNT(*) FROM #T WHERE Rate = @Rate);SET STATISTICS TIME OFF;SELECT ElapsedMS=DATEDIFF(millisecond, @StartDT, GETDATE());SELECT @StartDT=GETDATE();PRINT 'Divide and Conquer Solution by Dwain.C';SET STATISTICS TIME ON;SELECT Shift INTO #T1FROM #T WHERE Rate = @Rate;DECLARE @Rows INT = @@ROWCOUNT;SELECT @Holder=RateFROM #TWHERE Shift IN (SELECT Shift FROM #T1)GROUP BY RateHAVING COUNT(*) = @Rows;SET STATISTICS TIME OFF;SELECT ElapsedMS=DATEDIFF(millisecond, @StartDT, GETDATE());SELECT @StartDT=GETDATE();PRINT 'Solution by Peso/Adam Machanic';SET STATISTICS TIME ON;WITH Target AS( SELECT Rate, Shift FROM #T WHERE Rate = @Rate)SELECT @Holder=c.RateFROM ( SELECT Rate, rc=COUNT(*) FROM #T GROUP BY Rate) aJOIN ( SELECT rc=COUNT(*) FROM Target) b ON b.rc <= a.rcJOIN #T AS c ON c.Rate = a.RateJOIN Target AS d ON d.Shift = c.ShiftGROUP BY c.RateHAVING COUNT(*) = MIN(b.rc);SET STATISTICS TIME OFF;SELECT ElapsedMS=DATEDIFF(millisecond, @StartDT, GETDATE());GODROP TABLE #T;DROP TABLE #T1;`From the statistics, I get these CPU/Elapsed time results:`Solution by Hunchback SQL Server Execution Times: CPU time = 1637 ms, elapsed time = 452 ms.Solution by Dwain.C SQL Server Execution Times: CPU time = 1467 ms, elapsed time = 473 ms.Divide and Conquer Solution by Dwain.C SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. SQL Server Execution Times: CPU time = 1169 ms, elapsed time = 301 ms.Solution by Peso/Adam Machanic SQL Server Execution Times: CPU time = 1996 ms, elapsed time = 2235 ms.`And these results are quite similar to the results SELECTED into the 4 results panes for elapsed MS:`4604803062263`Comments:- I eliminated Sean's solution because I believe he's solving a different problem. But of course since the OP has confirmed that he prefers Sean's solution, I have to assume that both Hunchback and I read the requirements wrong.- The result for my last suggestion (Peso/Adam Machanic solution) was probably impacted by the <= I had to use in the first JOIN. I believe their solution was based on the no remainder problem posed by Mr. Celko.I was surprised that Divide and Conquer came in at about 30% faster. 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 T.Ashish SSCrazy Group: General Forum Members Points: 2571 Visits: 639 Thanks Dwain.CKindly ignore my earlier post, I missed it completely. Actually, Other four solutions are giving accurate resultsMy results goes as below: 1.hunchbackWITH C1 AS (SELECT Shift FROM test12 WHERE Rate = 4)SELECT A.Rate FROM test12 AS A INNER JOIN C1 AS B ON A.Shift = B.ShiftGROUP BY A.Rate HAVING COUNT(*) = (SELECT COUNT(*) FROM C1);Table 'test12'. Scan count 2, logical reads 48 Query Cost relative to batch = 21%2.dwain.cSELECT Rate FROM test12WHERE Shift IN (SELECT Shift FROM test12 WHERE Rate = 4)GROUP BY Rate HAVING COUNT(*) = (SELECT COUNT(*) FROM test12 WHERE Rate = 4);Table 'test12'. Scan count 2, logical reads 48Query Cost relative to batch = 21%3.dwain.c (divide and concur)SELECT Shift INTO #T FROM @T WHERE Rate = @Rate; DECLARE @Rows INT = @@ROWCOUNT;SELECT Rate FROM @TWHERE Shift IN (SELECT Shift FROM #T)GROUP BY Rate HAVING COUNT(*) = @Rows;GODROP TABLE #T;Table 'test12'. Scan count 1, logical reads 2'#T_____00000000000D'. Scan count 1, logical reads 22Table 'test12'. Scan count 1, logical reads 2Query Cost relative to batch = 23%4.dwain.cWITH Target AS(SELECT Rate, Shift FROM test12 WHERE Rate = 4)SELECT c.RateFROM (SELECT Rate, rc=COUNT(*) FROM test12 GROUP BY Rate) aJOIN (SELECT rc=COUNT(*) FROM Target) b ON b.rc <= a.rcJOIN test12 AS c ON c.Rate = a.RateJOIN Target AS d ON d.Shift = c.ShiftGROUP BY c.RateHAVING COUNT(*) = MIN(b.rc);Table 'test12'. Scan count 8, logical reads 54,Query Cost relative to batch = 35%So, Cost wise, 1 and 2 are performing better then 3.ElapsedMS is as below:990956960 (Divide and Conquer)2723I could not get "Divide and Conquer" at first place.Thanks again everyone for putting your efforts. dwain.c SSC-Forever Group: General Forum Members Points: 43905 Visits: 6431 T.Ashish (9/27/2013)Thanks Dwain.CKindly ignore my earlier post, I missed it completely. Actually, Other four solutions are giving accurate resultsMy results goes as below: 1.hunchbackWITH C1 AS (SELECT Shift FROM test12 WHERE Rate = 4)SELECT A.Rate FROM test12 AS A INNER JOIN C1 AS B ON A.Shift = B.ShiftGROUP BY A.Rate HAVING COUNT(*) = (SELECT COUNT(*) FROM C1);Table 'test12'. Scan count 2, logical reads 48 Query Cost relative to batch = 21%2.dwain.cSELECT Rate FROM test12WHERE Shift IN (SELECT Shift FROM test12 WHERE Rate = 4)GROUP BY Rate HAVING COUNT(*) = (SELECT COUNT(*) FROM test12 WHERE Rate = 4);Table 'test12'. Scan count 2, logical reads 48Query Cost relative to batch = 21%3.dwain.c (divide and concur)SELECT Shift INTO #T FROM @T WHERE Rate = @Rate; DECLARE @Rows INT = @@ROWCOUNT;SELECT Rate FROM @TWHERE Shift IN (SELECT Shift FROM #T)GROUP BY Rate HAVING COUNT(*) = @Rows;GODROP TABLE #T;Table 'test12'. Scan count 1, logical reads 2'#T_____00000000000D'. Scan count 1, logical reads 22Table 'test12'. Scan count 1, logical reads 2Query Cost relative to batch = 23%4.dwain.cWITH Target AS(SELECT Rate, Shift FROM test12 WHERE Rate = 4)SELECT c.RateFROM (SELECT Rate, rc=COUNT(*) FROM test12 GROUP BY Rate) aJOIN (SELECT rc=COUNT(*) FROM Target) b ON b.rc <= a.rcJOIN test12 AS c ON c.Rate = a.RateJOIN Target AS d ON d.Shift = c.ShiftGROUP BY c.RateHAVING COUNT(*) = MIN(b.rc);Table 'test12'. Scan count 8, logical reads 54,Query Cost relative to batch = 35%So, Cost wise, 1 and 2 are performing better then 3.ElapsedMS is as below:990956960 (Divide and Conquer)2723I could not get "Divide and Conquer" at first place.Thanks again everyone for putting your efforts.#1 and 2 have effectively identical execution plans so any timing variances you're seeing with those is probably random and multiple testing runs probably would swing one way or the other.#3 (Divide and Conquer) has an advantage that will likely grow depending on the number of rows in your table (the more rows, the more the initial INSERT capturing the row count will help). I think anyway. 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 Sean Lange SSC Guru Group: General Forum Members Points: 147693 Visits: 18565 Well I guess I didn't quite get the requirements. Chock that up to a lack of details. This thread could serve as a good example of why it is so important to provide those details. ;-) _______________________________________________________________Need help? Help us help you. Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.Need to split a string? Try Jeff Modens splitter.Cross Tabs and Pivots, Part 1 – Converting Rows to Columns Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs Understanding and Using APPLY (Part 1)Understanding and Using APPLY (Part 2) T.Ashish SSCrazy Group: General Forum Members Points: 2571 Visits: 639 #3 (Divide and Conquer) has an advantage that will likely grow depending on the number of rows in your table (the more rows, the more the initial INSERT capturing the row count will help). I think anyway.I will keep that in mind.

## 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      SQL Server Security Skills      Question of the Day (QOD) Microsoft Access      Microsoft Access Products and Books      Third Party Products         SQLCentric         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Sonasoft         Golden Gate Software         Idera         Lumigent         Red Gate Software         ApexSQL         Quest Software         CA      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12