我寫了我的數據透視SQL,它正在工作。當前的SQL語句如下,我將展示如何返回數據的示例。我需要添加一列,這是它的炸彈:PIVOT 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.在我的選擇中,我認爲只需在查詢中添加「總計」即可,但每次都會收到無效的列。如果您希望該行的總,你可以簡單地添加列在一起,得到總
Msg 207, Level 16, State 1, Line 6 Invalid column name 'Total'.
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
簡單的甜! – gmang
是的,有時它是我們傾向於忽略的簡單東西,只需要另一組眼睛。 :) – Taryn