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)

  • This is a weird one...

    would something like this do the trick?

    declare @Total decimal(18,2)

    select @Total = sum(number)

    from #temp

    create table #temp2

    (

    customer varchar(15),

    number int,

    Ranking int

    )

    insert #temp2

    select customer,

    Number,

    ranking = row_number() over(order by number desc)

    from #temp

    select 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

    )sub

    where round((cast(Running as decimal(10,2))/ cast(@Total as decimal(10,2)))*100, 0) <= 60

    drop 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

    *****************/