case 语句中的多次计算不是 运行
Multiple Calculations in case statement not running
我正在尝试 运行 一个查询,该查询获取两个不同变量的平均值,然后计算它们之间的差值。但是,我不断收到错误消息,即查询无法识别第二次计算中的变量名称。我一直在四处寻找,但我觉得我只是在这里错过了一个简单的步骤
这是完整的查询
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
您不能在同一个 select
子句中使用给定列的 alias name
你需要写成子查询或者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
我正在尝试 运行 一个查询,该查询获取两个不同变量的平均值,然后计算它们之间的差值。但是,我不断收到错误消息,即查询无法识别第二次计算中的变量名称。我一直在四处寻找,但我觉得我只是在这里错过了一个简单的步骤
这是完整的查询
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
您不能在同一个 select
子句中使用给定列的 alias name
你需要写成子查询或者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