同列查询不同条件
Same column query for different conditions
我有一个如下所示的table,请帮助我构建它。
示例:
column 1 column 2
111111 100
111111 101
111111 102
222222 101
222222 102
333333 100
所以我正在寻找 column1,它的同一列只有 100 而不是 101 或 102。
从我上面的例子来看,333333 100
正是我要找的,它有 100 但没有 101 和 102。
尝试 not exists
运算符
SELECT *
FROM table t1
WHERE column2 = 100
AND NOT EXISTS (
SELECT * FROM table t2
WHERE t1.column1 = t2.column1
AND t2.column2 in (101, 102)
)
如果您想要 column1
值,可以使用 group by
和 having
:
select column1
from t
group by column1
having sum(case when column2 = 100 then 1 else 0 end) > 0 and
sum(case when column2 in (101, 102) then 1 else 0 end) = 0;
如果您只关心这些三个值,您可以将其简化为:
select column1
from t
where column2 in (100, 101, 102)
group by column1
having max(column2) = 100;
听起来您可能正在尝试进行数据透视查询:
我有一个如下所示的table,请帮助我构建它。
示例:
column 1 column 2
111111 100
111111 101
111111 102
222222 101
222222 102
333333 100
所以我正在寻找 column1,它的同一列只有 100 而不是 101 或 102。
从我上面的例子来看,333333 100
正是我要找的,它有 100 但没有 101 和 102。
尝试 not exists
运算符
SELECT *
FROM table t1
WHERE column2 = 100
AND NOT EXISTS (
SELECT * FROM table t2
WHERE t1.column1 = t2.column1
AND t2.column2 in (101, 102)
)
如果您想要 column1
值,可以使用 group by
和 having
:
select column1
from t
group by column1
having sum(case when column2 = 100 then 1 else 0 end) > 0 and
sum(case when column2 in (101, 102) then 1 else 0 end) = 0;
如果您只关心这些三个值,您可以将其简化为:
select column1
from t
where column2 in (100, 101, 102)
group by column1
having max(column2) = 100;
听起来您可能正在尝试进行数据透视查询: