在处理案例时整理id

mklgxw1f  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(315)

如何整理身份证´当我有一张table

CAR
ID      COLOR
1       Red
1       Black
2       BLUE
2       Black
3       Yellow
3       Red

我的目标是,所有的ID谁有颜色“红色”被抛出,所以只是 ID = 2 这是我的结果。通过我的sql,我可以找到带有红色的id Filter = 1 但它们仍然出现是因为 ID = 1 也可以是黑色(或者id=3可以是黄色),这样 Filter = 0 然后就通过了。

with SORTOUT as
(
ID,
CASE WHEN
COLOR = RED THEN 1
ELSE 0
END AS FILTER
FROM TABLE
)
SELECT * FROM ID_TABLE T1
JOIN SORTOUT T2 on (T1.ID = T2.ID)
WHERE FILTER = 0
7lrncoxx

7lrncoxx1#

如果只需要id,请使用聚合:

select id
from id_table
group by id
having sum(case when color = 'RED' then 1 else 0 end) = 0;

如果需要原始行,可以使用 not exists :

select i.*
from id_table i
where not exists (select 1
                  from id_table i2
                  where i2.id = i.id and i2.color = 'RED'
                 );
yeotifhr

yeotifhr2#

您可以使用简单的选择查询来实现这一点,

SELECT * FROM ID_TABLE WHERE COLOR != 'Red';

如果你还需要 CASE 声明,您可以使用下面的

SELECT ID, COLOR, 
CASE WHEN COLOR = 'Red' THEN 1 ELSE 0 END AS Val
FROM ID_TABLE WHERE CASE WHEN COLOR = 'Red' THEN 1 ELSE 0 END = 0;

SELECT ID, COLOR FROM
(SELECT ID, COLOR, 
CASE WHEN COLOR = 'Red' THEN 1 ELSE 0 END AS Val
FROM ID_TABLE) qry
WHERE Val = 0;

相关问题