连接的最大计数

时间:2010-04-08 17:08:06

标签: sql select join max

我有3张桌子:

用户:

Id   Login
1    John
2    Bill
3    Jim

计算机:

Id   Name
1    Computer1
2    Computer2
3    Computer3
4    Computer4
5    Computer5

会话

UserId   ComputerId   Minutes
1        2            47
2        1            32
1        4            15
2        5            5
1        2            7
1        1            40
2        5            31

我想显示这个结果表:

Login   Total_sess   Total_min   Most_freq_computer   Sess_on_most_freq   Min_on_most_freq
John    4            109         Computer2            2                   54
Bill    3            68          Computer5            2                   36
Jim     -            -           -                    -                   -

我自己只能用以下内容覆盖前3列:

SELECT Login, COUNT(sessions.UserId), SUM(Minutes) FROM users
LEFT JOIN sessions
ON users.Id = sessions.UserId GROUP BY users.Id

以及其他一些列:

SELECT main.*
FROM (SELECT UserId, ComputerId, COUNT(*) AS cnt ,SUM(Minutes)
FROM sessions
GROUP BY UserId, ComputerId) AS main
INNER JOIN (
SELECT ComputerId, MAX(cnt) AS maxCnt FROM (
SELECT ComputerId, UserId, COUNT(*) AS cnt FROM sessions GROUP BY ComputerId, UserId
)
AS Counts GROUP BY ComputerId) 
                    AS maxes
ON main.ComputerId = maxes.ComputerId
AND main.cnt = maxes.maxCnt

但我需要在一个查询中获得整个结果表。我觉得我做错了。需要帮助。

1 个答案:

答案 0 :(得分:3)

你在这里:

SELECT    u.login, t1.total_sess, t1.total_min, t2.mf, t2.sess_mf, t2.min_mf
FROM      users u
LEFT JOIN (
  SELECT   userid, COUNT(minutes) AS total_sess, SUM(minutes) AS total_min
  FROM     sessions
  GROUP BY userid
) AS t1 ON t1.userid = u.id
LEFT JOIN (
  SELECT   userid, name AS mf, COUNT(*) AS sess_mf, SUM(minutes) AS min_mf
  FROM     sessions s
  JOIN     computers c ON c.id = s.computerid
  GROUP BY userid, computerid
  HAVING   COUNT(computerid) >= ALL(SELECT   COUNT(*)
                                    FROM     sessions s2
                                    WHERE    s2.userid = s.userid
                                    GROUP BY s2.computerid)
) AS t2 ON t2.userid = u.id

我正在使用MySQL语法,但它应该非常便携。

如果您还需要更多信息,请随时提出!

编辑:我更新了查询,前一个错误:(