[英]In standard SQL, how do I select rows such that for each unique value in one column, all of the values in another column are a specified value?
In standard SQL, how do I select rows such that for each unique value in one column, all of the values in another column are a specified value? 在标准SQL中,如何选择行,以便对于一列中的每个唯一值,另一列中的所有值都是指定值?
For example, in the table below, I want to select all values of column c_1 where the value of c_s is 'd' for each distinct value of c_1. 例如,在下表中,我要为c_1的每个不同值选择c_1列的所有值,其中c_s的值为“ d”。 So for c_1 = '2', all values of c_s are 'd'.
因此,对于c_1 ='2',c_s的所有值均为'd'。 Same for c_1 = '3'.
对于c_1 ='3'相同。 This is not, however, the case for c_1 = '1', '4', or '5'.
但是,对于c_1 ='1','4'或'5'并非如此。
Here is my table: 这是我的桌子:
id | c_1 | c_2 | c_s
----+------+---------+--------
1 | 1 | 1 | d
2 | 1 | 2 |
3 | 2 | 1 | d
4 | 2 | 2 | d
5 | 2 | 3 | d
6 | 3 | 1 | d
7 | 4 | 1 | r
8 | 5 | 1 | d
9 | 5 | 2 | r
Here is what I would like to return from my sql query: 这是我想从我的SQL查询返回的内容:
c_1 | c_2 | c_s
----+---+--------
2 | 1 | d
3 | 1 | d
(I'm not sure how to phrase this question - key words, etc. - so please excuse me if there is better phrasing that would lead to a solution that is already posted here.) (我不确定该如何表达这个问题-关键字等-所以请原谅我,如果有更好的措辞可以导致已经在此处发布解决方案的话。)
You can do this with GROUP BY
and HAVING
: 您可以使用
GROUP BY
和HAVING
来做到这一点:
SELECT c_1
, MIN(c_2) AS c_2
, MAX(c_s) AS c_s
FROM Table1
GROUP BY c_1
HAVING MIN(CASE WHEN c_s = 'd' THEN 1 ELSE 0 END)
+ MAX(CASE WHEN c_s = 'd' THEN 1 ELSE 0 END) = 2
Demo: SQL Fiddle 演示: SQL Fiddle
In your example output you chose 1
for c_2
even though other values exist, so I used MIN()
, but if you wanted a different value to be chosen that logic could be adjusted. 在示例输出中,即使存在其他值,您
c_2
选择1
,所以我使用MIN()
,但是如果您希望选择其他值,则可以调整逻辑。
My answer is very similar to goat CO's. 我的答案与山羊CO非常相似。 I check the count for each value and compare it to the number of D's.
我检查每个值的计数并将其与D的数量进行比较。
select
c_1 as 'c_1',
min(c_2) as 'c_2',
min(c_s) as 'c_s'
from yourTable
group by c_1
having count(1) = sum(case when c_s = 'd' then 1 else 0 end)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.