0

我有一个USERS包含两列 ( RID, USERNAME) 的表,我只是通过RID获取USERNAME

我将传递 4 个参数作为 User1、User2、User3、User4RID 现在我想要如下结果:

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

它工作正常,但是当我通过NULL任何 USER's时它失败了RID。我不知道该怎么做。

4

3 回答 3

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
于 2013-09-16T11:39:21.310 回答
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)
于 2013-09-16T11:41:34.913 回答
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)

希望能帮助到你。

问候,

于 2013-09-16T12:36:11.547 回答