我在下面有一个查询。但是在最后选择的两个字段中,USDVal&运行查询时,cp是无效的列名。我不明白为什么呢?
因为如果我运行下面的查询而不包括最后一行(“as source ..”),那么查询就会运行。
;with s as
(
select cp, mktVal, date
from tblDaily
where date = '2017-01-30' and id = 'SFAB'
), h as
(
select idMK, name, cp, wgt
from tblDrift
where date = '2017-03-30' and idSub = 'V12' and wgt <> 0
), m as
(
select h.idMK, h.name, h.wgt * s.mktVal as USDVal, h.cp
from h left join s on h.cp = s.cp
)
select idMK, name, USDVal, cp from m
as source pivot(max(USDVal) for cp in ([BPP],[NCV])) as pvt
答案 0 :(得分:1)
尝试将最后两行更改为以下内容:
SELECT pvt.*
FROM
(
select idMK, name, USDVal, cp from m
) as source
pivot(max(USDVal) for cp in ([BPP],[NCV])) as pvt