SQL:从多个选项中选择,通过表连接条件

时间:2010-02-24 18:36:22

标签: sql sql-server join

无法理解这个......

我有3张这样的表:

Computers
---------
Id
Name


ComputerLogins
--------------
Computer_Id
User_Id
NumberOfLogins


Users
-----
Id
Name

计算机“通过”ComputerLogins“拥有并属于许多”用户“。

示例数据:

Computers:                  Id     Name
                             1  "Alpha"
                             2   "Beta"
                             3  "Gamma"

Users:                      Id     Name
                             1    "Joe"
                             2   "Fred"

ComputerLogins:    Computer_Id  User_Id  NumberOfLogins
                             1        1               5
                             1        2              12
                             2        1              10
                             2        2               6
                             3        1               2
                             3        2               4

我正在尝试构建一个视图,它将为Computers中的每条记录输出一行,并通过ComputerLogins中的MAX(NumberOfLogins)加入Users行。

期望的输出:

Computer_Id    User_Id    NumberOfLogins
          1          2                12
          2          1                10
          3          2                 4

你能建议一个能产生所需输出的视图查询吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

使用:

CREATE VIEW your_view AS 
 SELECT c.id AS computer_id,
        u.id AS user_id,
        COUNT(*) AS NumberOfLogins
   FROM COMPUTERS c
   JOIN COMPUTERLOGINS cl ON cl.computer_id = c.id
   JOIN USERS u ON u.id = cl.user_id
GROUP BY c.id, u.id

答案 1 :(得分:1)

SELECT
    CL.*, U.* --change this as needed
FROM
    (
    SELECT 
       Computer_ID, MAX(NumberOfLogins) AS NumberOfLogins
    FROM
       ComputerLogins
    GROUP BY
       Computer_ID
    ) maxC
    JOIN
    ComputerLogins CL On maxC.Computer_ID = CL.Computer_ID AND maxC.NumberOfLogins = CL.NumberOfLogins
    JOIN
    Users U On CL.User_ID = U.ID

包裹视图等