Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select top percent, in SQL Server, is off by 1?

I want to use select statement to get 10% from 3661 records table. But I get 367 records in return, but I want only 366 records; but when I put 50%, I want to get 1831 records, not 1830 records. here is the statement I use:

SELECT top 10 percent *
FROM table_a
like image 492
user1188125 Avatar asked Dec 13 '25 13:12

user1188125


1 Answers

Unfortunately, that's just how the TOP x PERCENT clause works (relevant part highlighted):

PERCENT

Indicates that the query returns only the first expression percent of rows from the result set. Fractional values are rounded up to the next integer value.

If you want a different rounding scheme, you will have to do the calculation yourself:

SELECT TOP (SELECT COUNT(*) / 10 FROM table_a) * FROM table_a

This would use an integer division, which truncates the fractional part, i.e., it rounds down.

Since you want 50% of 3661 to yield 1831, I guess you want "round half up", which you would get using the ROUND function:

SELECT TOP (SELECT CONVERT(int, ROUND(COUNT(*) / 10.0, 0)) FROM table_a) * FROM table_a

Note that 10.0 instead of 10 is required to force a floating-point division instead of an integer division.

like image 186
Heinzi Avatar answered Dec 15 '25 13:12

Heinzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!