[英]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. 我有一个SQL问题,我一直在努力,希望有人可以提供帮助。
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'. 我需要做的是返回TEAM的值,其中任何STEPx的所有值都是'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'. 因此,在上面的例子中,我需要返回TEAM 001和002,因为在TEAM 001中,STEP3的所有值都是'N',而在TEAM 002中,STEP1的所有值都是'N'。
Any help would be much appreciated. 任何帮助将非常感激。
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 这是一个小提琴: 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. 最好规范化数据,以便有一个名为
STEP
的int列和每个团队/用户/步骤一行。 This would make your query much less awkward. 这将使您的查询更不尴尬。
I went the other way, but Blorgbeard was much faster than me. 我走了另一条路,但Blorgbeard比我快得多。
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
There is no pure sql-based solution, but each conrete database may have its own way to iterate over all columns. 没有纯粹的基于sql的解决方案,但每个conrete数据库可能有自己的方式迭代所有列。
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" 在它之后,很容易加入这个表的团队并用“Y”过滤所有团队
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.