Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 获取两行具有特定值的列_Sql - Fatal编程技术网

Sql 获取两行具有特定值的列

Sql 获取两行具有特定值的列,sql,Sql,我有一张这样的桌子: | col1 | col2 | |------|------| | a | 1 | | a | 2 | | a | 3 | | b | 1 | | b | 3 | | c | 1 | | c | 2 | 我需要找到col1的值,其中存在具有相同col1值的两行,其col2值分别为1和2 结果将是: | col1 | |------| | a | | c | 您可以使用所需的c

我有一张这样的桌子:

| col1 | col2 |
|------|------|
| a    | 1    |
| a    | 2    |
| a    | 3    |
| b    | 1    |
| b    | 3    |
| c    | 1    |
| c    | 2    |
我需要找到
col1
的值,其中存在具有相同
col1
值的两行,其col2值分别为1和2

结果将是:

| col1 |
|------|
| a    |
| c    |

您可以使用所需的
col2
值筛选行,然后按
col1
分组,并仅使用
count=2

select  col1
from    yourTable
where   col2 in (1, 2)
group by col1
having  count(distinct col2) = 2

您可以使用所需的
col2
值筛选行,然后按
col1
分组,并仅使用
count=2

select  col1
from    yourTable
where   col2 in (1, 2)
group by col1
having  count(distinct col2) = 2

另一个解决办法是

select col1
from your_table
group by col1
having sum(case when col2 = 1 then 1 else 0 end) > 0
   and sum(case when col2 = 2 then 1 else 0 end) > 0

另一个解决办法是

select col1
from your_table
group by col1
having sum(case when col2 = 1 then 1 else 0 end) > 0
   and sum(case when col2 = 2 then 1 else 0 end) > 0