使用select语句作为列之一

时间:2012-09-11 20:58:15

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

我有一个问题:

select 
      index_imsid
    , SUM(weighted_value) sumWeightedValue
    , (
        select 
              top 1 percentof
            , [Plan_Name_OR_Payment_Type] 
        from [v_PlanPerProvider1] 
        where [PLAN_RANK]=1
      ) plan1
from [v_PlanPerProvider1]
where plan_rank between 1 and 10
group by index_imsid
order by 1

我收到此错误:

  

Msg 116,Level 16,State 1,Line 3
  当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式。

你能帮我理解为什么我会收到这个错误吗?

它似乎不喜欢select语句作为列之一?

2 个答案:

答案 0 :(得分:6)

它不喜欢您在子查询中选择两列。您一次只能选择一列。

  select index_imsid, SUM(weighted_value) sumWeightedValue,
    (select top 1 percentof from [v_PlanPerProvider1] where [PLAN_RANK]=1) percentof
    (select top 1 [Plan_Name_OR_Payment_Type] from [v_PlanPerProvider1] where [PLAN_RANK]=1) Plan_Name_OR_Payment_Type
  from [v_PlanPerProvider1]
  where plan_rank between 1 and 10
  group by index_imsid
  order by 1

答案 1 :(得分:2)

或者你可以这样做:

select  
    t1.index_imsid, SUM(t1.weighted_value) sumWeightedValue, t2.percentof, t2.[Plan_Name_OR_Payment_Type]
from [v_PlanPerProvider1] t1
cross join (select top 1 percentof, [Plan_Name_OR_Payment_Type] from [v_PlanPerProvider1] where [PLAN_RANK]=1) t2 
where t1.plan_rank between 1 and 10 
group by t1.index_imsid, t2.percentof, t2.[Plan_Name_OR_Payment_Type]
order by 1