HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Find top by values by percents using range in SQL Server

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
topserversqlrangepercentsusingfindvalues

Problem

What will be easier way to group records by range of percents.

Here what I try to accomplish

Select top percents between 50 and 75 * from myTable order by PKI


Here is way I did this but I have felling that it cloud be much much easier

select 
    top(25) percent 
     *
from myTable
where id not in (
            select 
                top(25) percent 
                 ID
            from myTable
            order by PKI
            )
order by PKI


This should be top 50 - 75 percents of my table ?

Is there better (nicer) way to do this.

Solution

Another way of doing it would be

WITH CTE
     AS (SELECT ID,
                PKI,
                ROW_NUMBER() OVER ( ORDER BY PKI) AS RN,
                COUNT(*) OVER()                   AS Cnt
         FROM   myTable)
SELECT ID,
       PKI
FROM   CTE
WHERE  RN BETWEEN 0.5 * Cnt AND 0.75 * Cnt

Code Snippets

WITH CTE
     AS (SELECT ID,
                PKI,
                ROW_NUMBER() OVER ( ORDER BY PKI) AS RN,
                COUNT(*) OVER()                   AS Cnt
         FROM   myTable)
SELECT ID,
       PKI
FROM   CTE
WHERE  RN BETWEEN 0.5 * Cnt AND 0.75 * Cnt

Context

StackExchange Database Administrators Q#33021, answer score: 6

Revisions (0)

No revisions yet.