Skip to content
Advertisement

Display rows where multiple columns are different

I have data that looks like this. Thousands of rows returned, but this is just a sample. Most days have the same numbers in them, but some do not. Note that ID 1 and 5 have identical numbers every day.

ID Sunday Monday Tuesday Wednesday Thursday Friday Saturday
1 26 26 26 26 26 26 26
2 44 44 30 30 44 44 44
3 55 55 55 55 80 90 55
4 12 12 43 43 43 43 43
5 36 36 36 36 36 36 36

I’d like to only return rows where the days of the week have different numbers.

In this case, the only IDs returned should be 2, 3 & 4.

What would I want this query to look like?

Thanks!

Advertisement

Answer

One idea that should work in most RDBMS (with some syntax tweaks) is the following. This is SQL Server compatible: pivot the days into rows and count the distinct values and filter accordingly:

select id
from t
cross apply (
    select Count(distinct d) from (
    values(sunday),(monday),(tuesday),(wednesday),(thursday),(friday),(saturday)
    )d(d)
)d(v)
where d.v>1
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement