我有两张表如下。我需要一个如下所示的结果。
table1
id name
-----------------
1 john
2 raju
3 gopi
4 sarath
table2
userid status
------------------
1 E
3 E
I need a query to select record from table like following
id name flag
---------------------
1 john In
2 raju Out
3 gopi In
4 sarath Out
如果状态为“E”的用户在结果集中显示为“In”,其他人则显示为“Out”
答案 0 :(得分:3)
简单的连接和案例
SELECT table1.*,
CASE WHEN table2.status='E' THEN 'In' ELSE 'Out' END
FROM table1 LEFT JOIN table2 on table1.id = table2.userid;
答案 1 :(得分:2)
我认为以下SQL对您有用。
select table1.id, table1.name, CASE WHEN table2.status='E' THEN 'In' ELSE 'Out' END
from table1 JOIN table2 on table1.id = table2.userid;