我正在SQL中创建一个数据透视表。我想让IsNull(ItemQty, 0)
工作。我有下面代码的方式不会起作用,因为它会抛出以下错误。如果我将顶部的Select语句更改为Select * from(),它将起作用。但是,那并不允许我做IsNull。
ShipWeekMod和ItemQty是vtc_ItemForecastSummary视图中CASE语句的结果。有什么想法吗?
消息207,级别16,状态1,行16无效的列名称' ShipWeekMod'。 消息207,级别16,状态1,行16无效的列名称' ItemQty'。
select
OfferTypeShipYear, EDPNO, OfferType, ShipYear, ShipWeekMod, IsNull(ItemQty, 0) as ItemQty
from
(
select OfferTypeShipYear, EDPNO, OfferType, ShipYear, ShipWeekMod, ItemQty as ItemQty from vtc_ItemForecastSummary
) DataTable
PIVOT
(
SUM(ItemQty)
FOR ShipWeekMod
IN (
[2],[4],[6],[8],[10],[12],[14],[16],[18],[20],[22],[24], [26],[28],[30],[32],[34],[36],[38],[40],[42],[44],[46],[48],[50],[52]
)
) PivotTable
答案 0 :(得分:2)
您无法在select中重复使用您转动的列。相反,您必须将isnull函数应用于pivot返回的每个列。由于这可能很繁琐,您可以考虑重写查询以使用动态sql。
应该看起来像这样:
select
OfferTypeShipYear, EDPNO, OfferType, ShipYear,
isnull([2],0) as [2],
isnull([4],0) as [4],
isnull([6],0) as [6],
isnull([8],0) as [8]
... etcetera
from (
select
OfferTypeShipYear, EDPNO, OfferType,
ShipYear, ShipWeekMod, ItemQty
from vtc_ItemForecastSummary
) DataTable
PIVOT (
SUM(ItemQty)
FOR ShipWeekMod
IN (
[2],[4],[6],[8],[10],[12],[14],[16],[18],[20],[22],[24],
[26],[28],[30],[32],[34],[36],[38],[40],[42],[44],[46],[48],[50],[52]
)
) PivotTable