我已经编写了我的数据透视 SQL,它正在工作。当前的 SQL 语句如下所示,我将展示如何返回数据的示例。我需要添加一列,这就是它爆炸的地方:
Select
ProductGroup,
Origin,
Destination,
[YEAR],
Isnull([Jan],0) as "Jan",
isnull([Feb],0) as "Feb",
isnull([Mar],0) as "Mar",
isnull([Apr],0) as "Apr",
isnull([May],0) as "May",
isnull([Jun],0) as "Jun",
isnull([Jul],0) as "Jul",
isnull([Aug],0) as "Aug",
isnull([Sep],0) as "Sep",
isnull([Oct],0) as "Oct",
isnull([Nov],0) as "Nov",
isnull([Dec],0) as "Dec"
FROM
(
SELECT
p.ProductGroup,
S.Origin,
S.FinalDest AS Destination,
SUBSTRING('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec', (Month(boldate) * 4) - 3, 3) as MonthAbreviated,
Year(BolDate) AS [Year],
Count(*) AS [Total]
-- ,COUNT(S.Purchase#) AS [TheTotal]
FROM
dbo.Contracts c INNER JOIN dbo.Purchases pu ON c.[Contract#] = pu.[Contract#]
INNER JOIN dbo.Products as p ON pu.Product = p.Product
INNER JOIN dbo.Shipments S ON pu.[Purchase#] = S.[Purchase#]
WHERE
Year(BolDate)<>1994 AND
pu.Cancelled=0 AND S.[Status]='L'
GROUP BY p.ProductGroup, S.Origin, S.FinalDest,Year(BolDate), SUBSTRING('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec', (Month(boldate) * 4) - 3, 3)
) AS SourceTable
PIVOT
(
sum( Total )
FOR MonthAbreviated IN ([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec])
) AS PivotTable
结果示例:
ProductGroup Origin Destination YEAR Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Nail Bath Toronto 2012 0 0 0 10 1 0 0 0 0 0 0 0
Nail Cedars Toronto 2011 0 0 0 0 0 0 0 0 0 0 25 53
我需要添加一个显示行总数的列。例如,第 1 行是 11,第 2 行是 78。在我的选择中,我认为只需将“Total”添加到查询中就可以了,但每次我都会得到一个无效的列。
换句话说,我收到此错误:
消息 207,级别 16,状态 1,第 6 行无效的列名称“总计”。
Select
ProductGroup,
Origin,
Destination,
[YEAR],
[Total],
Isnull([Jan],0) as "Jan",
isnull([Feb],0) as "Feb",
isnull([Mar],0) as "Mar",
isnull([Apr],0) as "Apr",
isnull([May],0) as "May",
isnull([Jun],0) as "Jun",
isnull([Jul],0) as "Jul",
isnull([Aug],0) as "Aug",
isnull([Sep],0) as "Sep",
isnull([Oct],0) as "Oct",
isnull([Nov],0) as "Nov",
isnull([Dec],0) as "Dec"
FROM
(
SELECT
p.ProductGroup,
S.Origin,
S.FinalDest AS Destination,
SUBSTRING('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec', (Month(boldate) * 4) - 3, 3) as MonthAbreviated,
Year(BolDate) AS [Year],
Count(*) AS [Total]
-- ,COUNT(S.Purchase#) AS [TheTotal]
FROM
dbo.Contracts c INNER JOIN dbo.Purchases pu ON c.[Contract#] = pu.[Contract#]
INNER JOIN dbo.Products as p ON pu.Product = p.Product
INNER JOIN dbo.Shipments S ON pu.[Purchase#] = S.[Purchase#]
WHERE
Year(BolDate)<>1994 AND
pu.Cancelled=0 AND S.[Status]='L'
GROUP BY p.ProductGroup, S.Origin, S.FinalDest,Year(BolDate), SUBSTRING('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec', (Month(boldate) * 4) - 3, 3)
) AS SourceTable
PIVOT
(
sum( Total )
FOR MonthAbreviated IN ([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec])
) AS PivotTable