使用Microsoft Access并且很难弄清楚如何获得所需的结果。我有两个链接表,在[床]上有一个内连接,两个表中都有以下数据。我希望选择[性别]不匹配的[房间号码](每个房间号码有多个不同的值)。我已经搜索了stackoverflow并且没有发现任何看起来都是组和选择不同的组[房间号]。
Table 1
-----------------
Room Number | Bed
101 | 101a
101 | 101b
101 | 101c
102 | 102a
102 | 102b
103 | 103a
103 | 103b
Table 2
-----------------
Bed | Gender
101a | Male
101b | Male
101c | Female
102a | Male
102b | Male
103a | Female
103b | Undefined
有了这个数据集,我希望它能够返回101和103室以及相关的性别。
SELECT ROOM_NO 来自RMGT_T_ROOMS INNER JOIN RMGT_T_ROOM_CONFIGS在RMGT_T_ROOMS.PK_BED_SPACE = RMGT_T_ROOM_CONFIGS.CK_BED_SPACE GROUP BY RMGT_T_ROOMS.FK_ROOM_NO 具有计数(不明显性)> 1
答案 0 :(得分:2)
inner join
和group by
怎么样?
select t1.room
from t1 inner join
t2
on t1.bed = t2.bed
group by t1.room
having min(gender) <> max(gender);
如果您知道只有两种性别,则可以将min(gender)
和max(gender)
添加到select
。
另一种方法使用exists
:
select t1.room, t2.gender
from t1 inner join
t2
on t1.bed = t2.bed
where exists (select 1
from t1 as t11 inner join
t2 as t22
on t11.bed = t22.bed
where t22.gender <> t2.gender
);
答案 1 :(得分:2)
你可以将这张桌子加入床上的身份证,并计算不同性别的数量:
SELECT room_number
FROM t1
JOIN t2 ON t1.bed = t2.bed
GROUP BY room_number
HAVING COUNT(DISTINCT gender) > 1