SQL查询-如何筛选出重复值
如果我有两个帐户(1和2),但我正在尝试筛选有苹果但没有桔子的帐户。根据这些数据,您将如何做到这一点 这就是我现在拥有的:SQL查询-如何筛选出重复值,sql,sql-server,tsql,Sql,Sql Server,Tsql,如果我有两个帐户(1和2),但我正在尝试筛选有苹果但没有桔子的帐户。根据这些数据,您将如何做到这一点 这就是我现在拥有的: SELECT * FROM products p join accounts a on a.id = p.id join ( SELECT account FROM products p join accounts a2 on a2.id = p.id WHERE products LIKE '%Apples%' ) a2.id = a.id W
SELECT *
FROM products p
join accounts a on a.id = p.id
join
(
SELECT account
FROM products p
join accounts a2 on a2.id = p.id
WHERE products LIKE '%Apples%'
) a2.id = a.id
WHERE products NOT LIKE '%Oranges%'
您的查询和示例数据不一致。根据数据: 实际上,您可以简单地使用示例中的
having
子句:
having max(product) = 'Apples'
这使用了“苹果”按字母顺序出现在“橙子”之前的事实
SELECT * FROM "YourTableName"
WHERE Account_# NOT IN (
SELECT Account_# FROM "TheSameTableNameAsMentionedBefore"
WHERE Product = "Oranges"
);
它应该会起作用。但我不确定我是否正确理解了你的问题。你提到了“无重复项”。我建议你看一看。
您可以使用
exists
select *
from your_table t1
where exists (select 1
from your_table t2
where t2.account_num=t1.account_num and product='Apples')
and not exists (select 1 from
your_table t2
where t2.account_num=t1.account_num and product='Oranges');
select *
from your_table t1
where exists (select 1
from your_table t2
where t2.account_num=t1.account_num and product='Apples')
and not exists (select 1 from
your_table t2
where t2.account_num=t1.account_num and product='Oranges');