2017-06-30 5 views
-1

CTE(Common Table Expression)テーブルから派生した値を変数に取り込もうとしました。何らかの理由で動作しないようです。以下はコードです共通テーブル式の後に変数を使用する

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

「CTE」の後の最初のステートメントは、「選択」ステートメントでなければなりません。あなたの変数をあなたの 'CTE'の上に宣言してください –

+0

結果からランダムな' AVG(Response) 'が' @ K4Resp'に割り当てられます –

+0

あなたの宣言の配置の他に、ここにいくつかの問題があります。変数は数値(5,2)として定義しますが、クエリでは数値(10,2)としてキャストします。また、スカラ変数の値を複数の行を持つクエリの結果に設定しています。 –

答えて

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 
+0

'group by 'を見ることによって、OPが' @ K4Resp'変数に割り当てられた正しい値を得られないと思います。 –

+0

@ K4Resp = CAST(数値(10,2)選択した値を変数に代入するので、 "as K4Response"を削除する必要があります。 –

+0

ありがとう@SergioPrats。 「K4Responseとして」を削除すると、問題が解決しました。 – Rajiv

関連する問題