错误:子查询返回的值超过1

时间:2014-08-25 16:20:40

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

我有像

这样的查询
    select U.UserId,
           U.FirstName,
           U.lastName,
           case when (u.Department = '' or u.Department is null) then
           (select c.Client from user us 
                  inner join filter f on us.UserId = f.UserId
                  inner join client c on f.ClientId = c.ClientId)
             else
            u.Department 
            end as Client

from user U

当我尝试运行上述查询时,我收到以下错误

“子查询返回的值超过1。当子查询跟随=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。”。< / p>

我可以使用任何替代查询进行上述查询

提前感谢。

2 个答案:

答案 0 :(得分:1)

您可以在子选择中引用外部用户表,如下所示:

select
    U.UserId,
    U.FirstName,
    U.lastName,
    case 
      when (u.Department = '' or u.Department is null) then (
        select
            c.Client
        from
            filter f
                inner join
            client c
                on f.ClientId = c.ClientId
        where
            u.UserId = f.UserId -- note refers to outer table
      ) else
        u.Department 
    end as Client
from
    [user] U

如果subselect仅为每个用户值返回一行,则此方法有效。如果它返回多个,你需要解释更多你想要做的事情。

答案 1 :(得分:0)

我想你想,如果当时部门为空或空白你需要从客户端表中获取客户端用于其他用户的部门吗? 如果是,那么下面的查询将帮助您。

select U.UserId,
   U.FirstName,
   U.lastName,
   case when (u.Department = '' or u.Department is null) then
   (select Top 1 c.Client from 
           filter f 
          inner join client c on f.ClientId = c.ClientId and u.UserId = f.UserId)
     else
    u.Department 
    end as Client
from [user] U;