Sql 如何选择同时具有“红色”和“黑色”的id?

Sql 如何选择同时具有“红色”和“黑色”的id?,sql,sql-server,oracle,plsql,oracle11g,Sql,Sql Server,Oracle,Plsql,Oracle11g,我想写一个简单的pl/sql或mssql 用于选择红色同时为黑色的车辆id 样本: 我想要的是: 以下是一种SQL标准方法,适用于任一数据库: select id from sample s group by id having sum(case when color = 'red' then 1 else 0 end) > 0 and sum(case when color = 'black' then 1 else 0 end) > 0; having子句中的每个

我想写一个简单的pl/sql或mssql

用于选择红色同时为黑色的车辆id

样本:

我想要的是:


以下是一种SQL标准方法,适用于任一数据库:

select id
from sample s
group by id
having sum(case when color = 'red' then 1 else 0 end) > 0 and
       sum(case when color = 'black' then 1 else 0 end) > 0;
having子句中的每个条件统计与其中一种颜色匹配的行数。只有具有每种颜色的ID才会包含在最终结果集中

编辑:


您可以在“分组依据”之前添加“红色”、“黑色”中的where颜色。根据数据和索引,这可以显著提高查询的性能。

这将仅选择ID:

select id 
    from mytable 
    where color in ('Red', 'Black')
    group by id
    having count(color) =2
将其用作内部选择,也可以获得颜色

select id, color
where color in ('Red', 'Black')
from mytable where id in (
    select id 
    from mytable 
    where color in ('Red', 'Black')
    group by id
    having count(color) =2
)
对于pl/sql,使用适当的索引:

SELECT DISTINCT Id
FROM   yourTable
WHERE  Color = 'Black' AND Id IN
       (SELECT DISTINCT Id FROM yourTable WHERE Color = 'Red')
很明显


不过,从文章中获得的收获总是能读到它们,这是一个数据库专家和有趣的作家,因为IN可能看起来效率低下,但在现代引擎上不一定如此。

这是针对sql server还是oracle的?其中一个就够了me@JensSchauder . . . mssql指的是SQL Server,pl/SQL指的是Oracle。OP显然也需要。3行黑/红/绿怎么样?我会试着把答案转回来。与拉马克的答案有什么不同?他假设表名为“yourtable”,而我假设表名为“MyTable”:-子选择中的不同是多余的。@Jenschauder:谢谢。在两个引擎上?我从来没有真正确定过…:-我的意思是,我当然希望如此……我不知道sql server。但甲骨文是100%。我确实看到了它导致的性能问题,因为它触发了一种完全无用的排序。@Jenschauder:这很有趣,我通常会用非常彻底的研究和发布的数据来支持这一点。有关详细信息,请参阅链接。
select ID from YourTable T1

where exists (select * from YourTable where ID = T1.ID and Color = 'Red')
  and exists (select * from YourTable where ID = T1.ID and Color = 'Black')
select id, color
where color in ('Red', 'Black')
from mytable where id in (
    select id 
    from mytable 
    where color in ('Red', 'Black')
    group by id
    having count(color) =2
)
SELECT DISTINCT Id
FROM   yourTable
WHERE  Color = 'Black' AND Id IN
       (SELECT DISTINCT Id FROM yourTable WHERE Color = 'Red')
select ID from YourTable T1

where exists (select * from YourTable where ID = T1.ID and Color = 'Red')
  and exists (select * from YourTable where ID = T1.ID and Color = 'Black')