其他列中的当前行值是多少?

时间:2017-12-18 19:39:49

标签: sql sql-server

我试图通过确定他们的ID userProfiles.UserProfilesId是否在字段UserProfiles.ManagerId中的任何位置来确定用户是否是管理员。我当前的sql语句说id无效。是否有我可以创建的子查询来确定此信息?

SELECT
      IsNull(PersonalTimeRemaining, 0) as PTO,
      UserProfiles.UserProfileId as id,
      us.Email,
      us.LastName + ', ' + us.FirstName,
      managers.Email as 'manager',
      case when PersonalTimeRemaining is null then 'hourly' else 'salary' end as salaryType,
      case when 
        EXISTS(SELECT * from UserProfiles where id = UserProfiles.UserProfileId)
      then 'User' else 'Manager' end as salaryType
  FROM UserProfiles
  inner join Users as us on us.UserId = UserProfiles.UserProfileId
  inner join Users as managers on managers.UserId = UserProfiles.ManagerId

2 个答案:

答案 0 :(得分:0)

这是一个简单的例子......在这种情况下,我使用表别名(T和T2)和相关的子查询来查询同一个表的managerID。

DECLARE @test TABLE (UserProfileID int, ManagerID int)
INSERT INTO @test VALUES (1, 4), (2, 4), (3, 4), (4, 5)

SELECT UserProfileID
      ,CASE WHEN EXISTS (SELECT T2.ManagerID
                           FROM @test T2
                          WHERE T2.ManagerID = T.UserProfileID
                        )
             THEN 'Manager'
             ELSE 'User'
       END AS salaryType

  FROM @test T

答案 1 :(得分:0)

不需要子查询或连接表两次,它只是:

SELECT COLUMN ..
       CASE WHEN UP.UserProfileId IS NULL THEN 'Manager' ELSE 'User' END AS SalaryType
FROM Users U LEFT JOIN UserProfiles UP ON 
     U.UserId = UP.UserProfileId

这是一个很好理解的简单例子:

CREATE TABLE Users (
    UserId INT
    -- Other columns
    );
CREATE TABLE UserProfiles (
    UserProfileId INT
    -- Other columns
    );

INSERT INTO Users VALUES
(1), (2);
INSERT INTO UserProfiles VALUES
(2);

SELECT U.UserId,
       CASE WHEN UP.UserProfileId IS NULL THEN 'Manager' ELSE 'User' END AS SalaryType
FROM Users U LEFT JOIN UserProfiles UP ON U.UserId = UP.UserProfileId;