Rounding Issue In SELECT TOP (n) PERCENT In T-SQL

There is a rounding issue In SELECT TOP (n) PERCENT In T-SQL, basically, TOP (n) PERCENT applies the CEIL function rather than FLOOR function. For instance, if there are total 4 valid rows, when 0 < n <= 25 would return 1 row, when 25 < n <= 50 would return 2 rows. If that is what you want, that is fine. If you want FLOOR function, it does not work. Following is the solution:

SELECT TOP
(
SELECT CONVERT(INT, COUNT(*)/4)
FROM dbo.dataset
WHERE Key_Column IS NOT NULL
) *
FROM dbo.dataset
WHERE Key_Column IS NOT NULL

Here, 4 is to generate 25% rows, and * is for all columns.

1 comment:

  1. Excellent information. Used it to answer QA when they wanted to know why the top 10% of 14 locations was 2. Might also need the fix if they push back in the future. Thanks

    ReplyDelete

Labels