Home Forums SQL Server 2005 T-SQL (SS2K5) How to return a certain percentage of rows (NOT TOP PERCENT QUESTION) RE: How to return a certain percentage of rows (NOT TOP PERCENT QUESTION)

  • 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',10

    insert into @Temp select'B',20

    insert into @Temp select'C',17

    insert into @Temp select'D',18

    insert into @Temp select'E',30

    insert into @Temp select'F',40

    insert into @Temp select'G',10

    insert into @Temp select'H',20

    insert into @Temp select'I',17

    insert into @Temp select'J',18

    insert into @Temp select'K',30

    insert into @Temp select'L',40

    DECLARE @Sum INT

    SELECT @Sum = SUM(number)

    FROM @Temp

    DECLARE @Percent FLOAT

    SET @Percent = @Sum * .6

    SELECT

    customer, Number, RunningTotal

    FROM

    (

    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 D

    WHERE

    RunningTotal <= @Percent -- Could add on some sort of varience if needed

    ORDER BY

    RunningTotal