在公用表表达式后使用变量

时间:2017-06-30 13:53:24

标签: sql sql-server tsql

我试图将从CTE(公用表表达式)表派生的值捕获到变量中。出于某种原因,它似乎不起作用。以下是代码:

WITH CTE
as
(
    select 
    Case 
        when target_title like '%P1%' then 'P1'
        when target_title like '%P2%' then 'P2'
        when target_title like '%P3%' then 'P3'
        when target_title like '%P4%' then 'P4'
    End as Priority,
    flag,
        case when flag='Response' then Business_Hours_MMTR end as Response,
        case when flag = 'Resolution' then Business_Hours_MMTR end as Resolution
    from Keurig..Response_Resolution
    where [Group] like '%Network%'
and datepart(month, Measurement_Stop) =  datepart(month, Getdate())-1
and (Target_Title like '%P1%' OR Target_Title like '%P2%' OR Target_Title like '%P3%' OR Target_Title like '%P4%')
)
Declare @K4Resp numeric(5,2);
Select @K4Resp = CAST(AVG(Response) as numeric(10,2)) as K4Response from CTE where flag = 'Response' and Priority = 'P4'
group by Priority, flag

1 个答案:

答案 0 :(得分:1)

common table expression之前移动您的声明。只有cte之后的语句才能引用cte。在这种情况下,那是您的declare

declare @K4Resp numeric(5, 2);
with CTE as (
  select 
      case 
        when target_title like '%P1%' then 'P1'
        when target_title like '%P2%' then 'P2'
        when target_title like '%P3%' then 'P3'
        when target_title like '%P4%' then 'P4'
      end as Priority
    , flag
    , case when flag = 'Response' then Business_Hours_MMTR end as Response
    , case when flag = 'Resolution' then Business_Hours_MMTR end as Resolution
  from Keurig..Response_Resolution
  where [Group] like '%Network%'
  and datepart(month, Measurement_Stop) = datepart(month, Getdate()) - 1
  and ( Target_Title like '%P1%'
     or Target_Title like '%P2%'
     or Target_Title like '%P3%'
     or Target_Title like '%P4%'
     )
)
select @K4Resp = CAST(AVG(Response) as numeric(5, 2))
from CTE
where flag = 'Response'
  and Priority = 'P4'
group by 
    Priority
  , flag