Neil
Neil

Reputation: 25

SQL - Select rows where all values in a column are the same

I have an SQL question I've been struggling with and hope someone can help.

I have the following data:

TEAM | USERID | STEP1 | STEP2 | STEP3 | STEP4 | STEP5
 001 | 000001 |   Y   |   Y   |   N   |   N   |   Y
 001 | 000002 |   Y   |   N   |   N   |   Y   |   Y
 002 | 000003 |   N   |   Y   |   Y   |   N   |   N
 002 | 000004 |   N   |   Y   |   Y   |   Y   |   Y
 003 | 000005 |   Y   |   N   |   N   |   Y   |   N
 003 | 000006 |   Y   |   Y   |   Y   |   N   |   Y


What I need to do is return the value of the TEAM where all values of any STEPx are 'N'.

So in the example above I would need TEAM 001 and 002 to be returned because in TEAM 001 all values of STEP3 are 'N', and in TEAM 002 all values of STEP1 are 'N'.

Any help would be much appreciated.

Upvotes: 2

Views: 142

Answers (3)

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48207

I went the other way, but Blorgbeard was much faster than me.

select TEAM
from TEAMS
group by TEAM
having
    count(case STEP1 when 'Y' then 1 end) = 0
or  count(case STEP2 when 'Y' then 1 end) = 0
or  count(case STEP3 when 'Y' then 1 end) = 0
or  count(case STEP4 when 'Y' then 1 end) = 0
or  count(case STEP5 when 'Y' then 1 end) = 0

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103535

select team
from table
group by team
having
    sum(case step1 when 'N' then 0 else 1 end) = 0
or  sum(case step2 when 'N' then 0 else 1 end) = 0
or  sum(case step3 when 'N' then 0 else 1 end) = 0
or  sum(case step4 when 'N' then 0 else 1 end) = 0
or  sum(case step5 when 'N' then 0 else 1 end) = 0

Here's a fiddle: http://sqlfiddle.com/#!6/ecbff/3

It may be better to normalize your data so that you have an int column named STEP and one row per team/user/step. This would make your query much less awkward.

Upvotes: 6

user996142
user996142

Reputation: 2883

There is no pure sql-based solution, but each conrete database may have its own way to iterate over all columns.

How ever, this approach is bad. You should normalize your database.

|TEAM|USER_ID|STEP_ID|VALUE|
|1   | 1     | 1     |  Y  |

After it, it it will be easy to join team with this tables and filter all teams with "Y"

Upvotes: 0

Related Questions