我想将列的多个值与另一列的单个值进行比较。我尝试了很多,但它给了我"没有选择行" 这是我的情景...
我有一张表 Bus_stop_table :
Bus_ID(FK)------ STOP_ID
201 ------------------- 401
201 ------------------- 402
201 -------------------- 403
202 ------------------- 401
202 ------------------- 405
203 ------------------- 403
203 ------------------- 406
我必须选择一个同时具有stop_id 401和403的bus_id,即201 但是当我试图找到它时,我没有得到预期的结果.. 这是我的疑问
SELECT BUS_ID,stop_id FROM BUS_STOP_TABLE WHERE STOP_ID =all(401,405);
和
SELECT BUS_ID,stop_id FROM BUS_STOP_TABLE WHERE STOP_ID 401 and STOP_ID =
405;
SELECT BUS_ID,stop_id FROM BUS_STOP_TABLE WHERE STOP_ID 401 and STOP_ID =
405 group by (bus_id , stop_id);
请有人帮助我。
答案 0 :(得分:4)
使用Group by
和Having
子句
SELECT Bus_ID
FROM Bus_stop_table
WHERE STOP_ID IN ( 401, 403 )
GROUP BY Bus_ID
HAVING Count(DISTINCT STOP_ID) = 2
或更灵活的方法
SELECT Bus_ID
FROM Bus_stop_table
GROUP BY Bus_ID
HAVING Sum(CASE STOP_ID WHEN 401 THEN 1 ELSE 0 END) > 0
AND Sum(CASE STOP_ID WHEN 403 THEN 1 ELSE 0 END) > 0