Showing posts with label Rounding. Show all posts
Showing posts with label Rounding. Show all posts

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.

Labels