返回经理的姓名,而不是经理的userId

时间:2019-12-04 18:57:19

标签: sql sql-server tsql

我正在尝试找出如何返回经理的姓名而不是经理的userId。

SELECT u.fname, 
        u.lname,
        ua.email,
        (
            SELECT distinct u.mgrUserid
            FROM users
            WHERE u.mgrUserid IS NOT NULL
        ) AS 'manager'
FROM dbo.quizzes_users qu
INNER JOIN dbo.quizzes q ON qu.quizId = q.quizId
INNER JOIN dbo.users u ON qu.userId = u.userId
INNER JOIN intela.dbo.users_all ua ON u.userId = ua.userId
WHERE qu.quizId = @quizId

上面的查询当前给我以下结果:

fname       lname           email                         manager 
John        Smith           john.smith@email.com          5 
Tim         Walker          tim.walker@email.com          1 

我正在尝试获得以下结果:

fname       lname           email                         manager
John        Smith           john.smith@email.com          Mike Jones
Tim         Walker          tim.walker@email.com          David Larson

2 个答案:

答案 0 :(得分:1)

我认为您想要一个相关的子查询:

    (SELECT um.lname
     FROM users um
     WHERE u.mgrUserid = um.Userid
    ) AS manager

答案 1 :(得分:1)

INNER JOIN是一个选项

SELECT u.fname, 
        u.lname,
        ua.email,
        mgr.[manager's name] AS 'manager'
FROM dbo.quizzes_users qu
INNER JOIN dbo.quizzes q ON qu.quizId = q.quizId
INNER JOIN dbo.users u ON qu.userId = u.userId
INNER JOIN dbo.users mgr ON u.mgrUserId = mgr.UserId
INNER JOIN intela.dbo.users_all ua ON u.userId = ua.userId
WHERE qu.quizId = @quizId