case语句中的多次计算未运行

时间:2015-01-09 19:55:45

标签: sql sql-server case case-when

我正在尝试运行一个查询,获取两个不同变量的平均值,然后计算它们之间的差异。但是,我不断收到错误,查询无法识别第二次计算中的变量名称。我一直在四处寻找,但我觉得我只是错过了一个简单的步骤

以下是完整查询

select 
DATEPART(dw,t1.Date),
DATENAME(dw,t1.Date),
AVG (CASE WHEN (rraw.Mode='Passive') THEN  T1.LengthSec + T1.Sec ELSE NULL
END) AS 'Passive',
AVG (CASE WHEN (rraw.Mode='Active') THEN  T1.Sec + T1.Sec ELSE NULL
END) AS 'Active'
then ( Passive - Active ) / Passive * 100.0 AS 'ModePrctDiff'
from bm.t1agent t1 with (nolock)
JOIN prc.Request rreq
on t1.id = rreq.t1ID
join PRC.Raw rraw with (nolock) 
on rreq.ID = rraw.Id
where t1.Date >= '2014-12-07'
GROUP BY  ROLLUP ((DATEPART(dw,t1.Date),DATENAME(dw,t1.Date)))

在then语句中发生错误。如果我在没有该部分的情况下运行它,我会获得这些结果

 Day Of Week    Passive       Active
 Sunday         350.54        370.54
 Monday         365.54        380.91

我希望读取结果

Day Of Week    Passive       Active  Difference
Sunday         350.54        370.54   xxxx
Monday         365.54        380.91   xxxx

1 个答案:

答案 0 :(得分:2)

您无法使用同一alias name子句中的列select

你需要把它写成子查询或cte。

with cte 
as 
(
    select 
    DATEPART(dw,t1.Date) as dw1,
    DATENAME(dw,t1.Date) as dw2,
    AVG (CASE WHEN (rraw.Mode='Passive') THEN  T1.LengthSec + T1.Sec ELSE NULL
    END) AS 'Passive',
    AVG (CASE WHEN (rraw.Mode='Active') THEN  T1.Sec + T1.Sec ELSE NULL
    END) AS 'Active'
    from bm.t1agent t1 with (nolock)
    JOIN prc.Request rreq
    on t1.id = rreq.t1ID
    join PRC.Raw rraw with (nolock) 
    on rreq.ID = rraw.Id
    where t1.Date >= '2014-12-07'
    GROUP BY  ROLLUP ((DATEPART(dw,t1.Date),DATENAME(dw,t1.Date))) 
)
select * , ( Passive - Active ) / Passive * 100.0 AS 'ModePrctDiff'
from cte