Log in  ::  Register  ::  Not logged in

## How to return a certain percentage of rows (NOT TOP PERCENT QUESTION)

 Author Message David-155102 UDP Broadcaster Group: General Forum Members Points: 1435 Visits: 459 I want to return all values that represent x% of the total values within a table. Here's some test data:`create table #temp (customer varchar(15),number int)insert into #temp select'A',10insert into #temp select'B',20insert into #temp select'C',17insert into #temp select'D',18insert into #temp select'E',30insert into #temp select'F',40insert into #temp select'G',10insert into #temp select'H',20insert into #temp select'I',17insert into #temp select'J',18insert into #temp select'K',30insert into #temp select'L',40select top 60 percent * from #temporder by number descdrop table #temp`When this is executed 60% of the total lines are returned but what I want is for it to return those rows whose 'number' values represent 60% of the total when added. So using my test data, 60% of the total would be represented by customers F, L, K and E because the sum of all the rows is 233 and the sum of F, L, K and E is 140 = 60%ThanksDavid mazzz SSCrazy Group: General Forum Members Points: 2489 Visits: 2661 I'm a little confused - how would you differentiate between sum(F, L, K) and sum (A, B, E, F, L) which also adds up to 140? ------------------------------------------------------------------------Bite-sized fiction (with added teeth) DCPeterson SSCertifiable Group: General Forum Members Points: 5067 Visits: 432 This is a weird one...would something like this do the trick?`declare @Total decimal(18,2)select @Total = sum(number)from #tempcreate table #temp2( customer varchar(15), number int, Ranking int)insert #temp2select customer, Number, ranking = row_number() over(order by number desc)from #tempselect customer, number, Running, pct = round((cast(Running as decimal(10,2))/ cast(@Total as decimal(10,2)))*100, 0)from( select customer, number, Ranking = ntile(12) over(order by number desc), Running = (select sum(number) from #temp2 t1 where t1.Ranking <= t.Ranking) from #temp2 t)subwhere round((cast(Running as decimal(10,2))/ cast(@Total as decimal(10,2)))*100, 0) <= 60drop table #temp2`This mess first orders the customers by Number Desc. Then calculates the running total and percentage of the running total against the total total, and returns those rows that add up to close to 60% without going over ("you're the next contestant on the Price is Right"...)This is based on an inference that you want to return the top 60% of customers by number.This works fine on a small set, but doubt it would be pretty on a large set of data...lots of table scans, sorts and temp table weirdness... /***************** If most people are not willing to see the difficulty, this is mainly because, consciously or unconsciously, they assume that it will be they who will settle these questions for the others, and because they are convinced of their own capacity to do this. -Friedrich August von Hayek *****************/ Lamprey13 SSCrazy Group: General Forum Members Points: 2180 Visits: 1657 I wasn't sure if you were looking for all combinations of Customers that meet that percentage or just starting with the min number or.???At anyrate, I just used a simple running total solution to get some results. Hopefully, it'll help:`DECLARE @Temp table (customer varchar(15),number int)insert into @Temp select'A',10insert into @Temp select'B',20insert into @Temp select'C',17insert into @Temp select'D',18insert into @Temp select'E',30insert into @Temp select'F',40insert into @Temp select'G',10insert into @Temp select'H',20insert into @Temp select'I',17insert into @Temp select'J',18insert into @Temp select'K',30insert into @Temp select'L',40DECLARE @Sum INTSELECT @Sum = SUM(number)FROM @TempDECLARE @Percent FLOATSET @Percent = @Sum * .6SELECT customer, Number, RunningTotalFROM ( SELECT customer, number, ( SELECT SUM(Number) FROM ( SELECT *,ROW_NUMBER() OVER (ORDER BY Number, Customer) AS RowNum FROM @Temp ) AS A WHERE RowNum <= T.RowNum ) AS RunningTotal FROM (SELECT *,ROW_NUMBER() OVER (ORDER BY Number, Customer) AS RowNum FROM @Temp) T ) AS DWHERE RunningTotal <= @Percent -- Could add on some sort of varience if neededORDER BY RunningTotal` David-155102 UDP Broadcaster Group: General Forum Members Points: 1435 Visits: 459 Thanks all, I'm out of the office so I'll test your solutions tomorrow.Just to clarify, what I wanted was to first order the rows in the temp table by number (desc) and then count 60% from the top downwards. Once 60% has been reached, or as close to, then stop. I see that you've already guessed that though! David-155102 UDP Broadcaster Group: General Forum Members Points: 1435 Visits: 459 Ok, I have had a chance to test out your solutions and am glad to say that after a bit of fiddling it is returning the data I need! We have a mixed environment here where some databases are not SQL 2005 compatible so the row numbering had to be done "the old way". Nevertheless, it is working now so thank you for your help. azhao 88633 Forum Newbie Group: General Forum Members Points: 2 Visits: 72 Hi David:Could you post your final solution? I have found out that two suggestions gave two different results and I would like to know the right one you have finally used.Thanks,Adrian Sean Pearce SSCertifiable Group: General Forum Members Points: 6268 Visits: 3436 `create table #temp (customer varchar(15),number int)insert into #temp select'A',1insert into #temp select'B',1insert into #temp select'C',1insert into #temp select'D',1drop table #temp`What is the expected results of selecting 25% of the above? The SQL Guy @ blogspot@SeanPearceSQLAbout Me

## 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 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 14 - Administration      SQL Server 14 - 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 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 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         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Sonasoft         SQLCentric         Golden Gate Software         Lumigent         Red Gate Software         Quest Software         ApexSQL         Idera      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss DTS Books          Discuss SQL Server 7.0 Books         Discuss SQL Server 2000 Books Notification Services      Administration Article Discussions Future Versions      SQL 12

## Search

 Copyright © 2002-2017 Redgate. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.