谁访问了房间

时间:2016-11-11 14:27:19

标签: sql transformation rank

我有一个包含useridroomidtimestamp字段的表格。

每个房间可能有不同的userIds

 userId1 roomid1 12:15:17
 userId1 roomid1 12:17:15
 userId2 roomid1 13:17:15 
 userId3 roomid2 12:15:15
 userId4 roomid2 12:15:18
 userId5 roomid2 12:15:25

我需要一个返回类似的查询:

  roomid            1           2           3        4           5
  roomid1      userid1       userid2     userid3
  roomid2      userid4       userid5     userid6   userid7    userid8

所以我可以看到不同的用户在整个游戏中访问了哪些不同的房间。

会议室内最多可容纳32位用户。

1 个答案:

答案 0 :(得分:0)

使用PIVOT

SELECT roomid, [userId1] AS userId1, [userId2] AS userId2, [userId3] AS userId3, [userId4] AS userId4, [userId5] AS userId5
FROM (SELECT timestamp, userid, roomid
      FROM yourtable) a
PIVOT
(COUNT (timestamp) 
 FOR userid IN ([userId1], [userId2], [userId3], [userId4], [userId5])
) AS b
ORDER BY b.roomid;

输出:

roomid  userId1 userId2 userId3 userId4 userId5
roomid1 2       1       0       0       0
roomid2 0       0       1       1       1

SQL小提琴:http://sqlfiddle.com/#!3/7df741/1/0