count of rows which are not divided by a number

Viewed 312

I have a column like below.

Value
_____
48
48
39
96
50

I want to divide this with 48.

From the above 5 values, row 1,2,4 can be divided, but 3,5 not. I have to do this with SQL.

EG:

select count(*) from tbl where value/42 
Result: 2
3 Answers

You are asking for the remainder when an integer is divided by 48. That has a specific name in mathematics, the modulo operation. This is actually a very interesting (to some people) part of number theory and group theory.

Most databases support the modulo operator or function via %. So the idea is:

select value
from t
where value % 48 = 0;

This might be:

where value mod 48 = 0
where mod(value, 48) = 0

depending on the database.

Another method is:

where floor(val / 48) * 48 = val

You can do that with a simple where clause

SELECT value FROM table WHERE value%48 = 0

The modulus operator returns the remainder for the division of the operands which in fact means we are checking if the numbers are divisible (remainder is zero when numbers are divisible)

So, if you are trying to count what’s not divisible then simple use below query

SELECT count(value) FROM table WHERE value%48 != 0

You can use modulus(%) to find the result. Check below query it will help you.

declare @tbl table (val int)

insert @tbl values(48),(48),(39),(96),(50)

select * from @tbl where val % 48 =0

Output

val
48
48
96
Related