我有一张这样的表:
table: roomMembers
roomid member
0 User1
0 User2
0 User3
1 User1
1 User2
1 User4
etc...
我需要一个SQL查询,它将返回UserX和UserY都是成员的roomid,例如,如果我要将它包装在一个函数中,它会是这样的:
findCommonRooms("User1", "User2");
在这种特殊情况下,它应该返回一个0和1的数组。
答案 0 :(得分:1)
如果我的理解是正确的,你可以很容易地找到之前实际上在同一个房间的成员。
CREATE TABLE roomMembers
(
roomid int,
member varchar(10)
);
INSERT INTO roomMembers VALUES (0,'Member1')
INSERT INTO roomMembers VALUES (0,'Member2')
INSERT INTO roomMembers VALUES (0,'Member3')
INSERT INTO roomMembers VALUES (1,'Member1')
INSERT INTO roomMembers VALUES (1,'Member2')
INSERT INTO roomMembers VALUES (1,'Member4')
这可以为您提供多人住宿的所有房间。
WITH q1
AS (
SELECT member
,count(*) total_count
FROM [dbo].[roomMembers]
GROUP BY member
HAVING count(*) > 1
)
SELECT r.roomid
,q1.member
FROM q1
JOIN dbo.roomMembers r ON r.member = q1.member
order by r.roomid;
希望这有帮助!
答案 1 :(得分:1)
此查询会为您提供两个' User1'和' User2'是会员。
SELECT roomid
FROM roomMembers
WHERE member in ('User1','User2')
GROUP BY roomid
HAVING COUNT(1) > 1