我试图找出如何在我的查询中添加yes / no列。这是我的情景:
模式
Table_A Table_B
------- -------
uid uid
color name
样本数据
Table_A Table_B
uid color uid name
1 red 1 Joe
1 blue 1 Joe
查询
SELECT table_a.color,table_b.name
FROM table_a
LEFT JOIN table_b ON table_a.id = table_b.id
WHERE table_a.color LIKE 'red'
这可以按预期工作,但是,我想添加一个名为' blue'如果Joe有蓝色和红色,请添加一个' Y'否则添加一个' N'
预期结果
uid color blue
1 red Y
答案 0 :(得分:1)
您可以尝试以下查询来获得结果
SELECT A.uid,A.color,case when cnt=2 then 'Y' else 'N' end as blue
FROM tableA as A
LEFT JOIN (select uid as id,count(distinct color)as cnt from tableA
WHERE lower(color) in ('blue', 'red') group by uid) as B ON A.uid = B.id
WHERE A.color='red'