选择将行作为列的语句

时间:2013-09-16 11:34:41

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我有一个包含两列(USERSRID)的表USERNAME 我只是将RID传递给USERNAME

我将传递4个参数作为User1,User2,User3,User4,其中RID 现在我想要结果如下:

Level1User Level2User Level3User Level4User
ABC        DEF        GHI        JKL

我尝试过以下查询:

SELECT
  L1.USERNAME AS Level1User,
  L2.USERNAME AS Level2User,
  L3.USERNAME AS Level3User,
  L4.USERNAME AS Level4User
FROM  [USERS] AS L1,
      [USERS] AS L2,
      [USERS] AS L3,
      [USERS] AS L4
WHERE L1.RID = @User1RID AND L2.RID = @User2RID AND L3.RID = @User3RID
      AND L4.RID = @User4RID

它工作正常,但是当我为任何USER的NULL传递RID时它失败了。 我不知道该怎么做。

3 个答案:

答案 0 :(得分:2)

使用标量子查询重写它,您不必再关心NULL了:

SELECT
  (SELECT USERNAME FROM [USERS] WHERE RID = @User1RID) AS Level1User,
  (SELECT USERNAME FROM [USERS] WHERE RID = @User2RID) AS Level2User,
  (SELECT USERNAME FROM [USERS] WHERE RID = @User3RID) AS Level3User,
  (SELECT USERNAME FROM [USERS] WHERE RID = @User4RID) AS Level4User

答案 1 :(得分:1)

您可以通过聚合执行此操作:

select max(case when u.RID = @User1RID then USERNAME end) as Level1User,
       max(case when u.RID = @User2RID then USERNAME end) as Level2User,
       max(case when u.RID = @User3RID then USERNAME end) as Level3User,
       max(case when u.RID = @User4RID then USERNAME end) as Level4User
from [users] u
where u.RID in (@User1RID, @User2RID, @User3RID, @User4RID)

答案 2 :(得分:0)

检查https://stackoverflow.com/a/13474228/2478298以获取答案

在你的情况下会做出

SELECT
  L1.USERNAME AS Level1User,
  L2.USERNAME AS Level2User,
  L3.USERNAME AS Level3User,
  L4.USERNAME AS Level4User
FROM  [USERS] AS L1,
      [USERS] AS L2,
      [USERS] AS L3,
      [USERS] AS L4
WHERE (L1.RID = @User1RID OR @User1RID IS NULL)
  AND (L2.RID = @User2RID OR @User2RID IS NULL)
  AND (L3.RID = @User3RID OR @User3RID IS NULL)
  AND (L4.RID = @User4RID OR @User4RID IS NULL)

希望它有所帮助。

此致