注意:您可以更改兼容級別。只要您將兼容級別更改爲更高的值,並且沒有依賴此數據庫的鏈接服務器等等,就不會影響任何內容。很明顯,如果你不確定,不要碰它
無論如何,有幾種方法可以做到這一點。這種方法使用UNION,我不知道你爲什麼說你不能使用這種方法,但是這給出了你的樣本期望值。
DECLARE @Temptable TABLE (
Company VARCHAR(5),
ProcessDate DATETIME,
OpExp DECIMAL,
Tax DECIMAL,
Total DECIMAL);
INSERT INTO @TempTable VALUES
('Comp1', getdate(), 1000, 100, 1100),
('Comp1', dateadd(year, -1, getdate()), 2000, 200, 2200),
('Comp1', dateadd(year, -2, getdate()), 3000, 300, 3300);
SELECT * FROM @TempTable
DECLARE @ReportStartYear int = 2017
SELECT
t.Company
, 'OpExp' as Val
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear -2 THEN OpExp ELSE 0 END) AS ColA
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear -1 THEN OpExp ELSE 0 END) AS ColB
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear THEN OpExp ELSE 0 END) AS ColC
, @ReportStartYear - 2 as ColACaption
, @ReportStartYear - 1 as ColBCaption
, @ReportStartYear as ColCCaption
FROM @Temptable t
GROUP BY t.Company
UNION ALL
SELECT
t.Company
, 'Tax' as Val
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear -2 THEN Tax ELSE 0 END) AS ColA
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear -1 THEN Tax ELSE 0 END) AS ColB
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear THEN Tax ELSE 0 END) AS ColC
, @ReportStartYear - 2 as ColACaption
, @ReportStartYear - 1 as ColBCaption
, @ReportStartYear as ColCCaption
FROM @Temptable t
GROUP BY t.Company
UNION ALL
SELECT
t.Company
, 'Total' as Val
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear -2 THEN Total ELSE 0 END) AS ColA
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear -1 THEN Total ELSE 0 END) AS ColB
, SUM(CASE YEAR(t.ProcessDate) WHEN @ReportStartYear THEN Total ELSE 0 END) AS ColC
, @ReportStartYear - 2 as ColACaption
, @ReportStartYear - 1 as ColBCaption
, @ReportStartYear as ColCCaption
FROM @Temptable t
GROUP BY t.Company
這將返回以下
Company Val ColA ColB ColC ColACaption ColBCaption ColCCaption
Comp1 OpExp 3000 2000 1000 2015 2016 2017
Comp1 Tax 300 200 100 2015 2016 2017
Comp1 Total 3300 2200 1100 2015 2016 2017
在報表中,您可以設置列標題是=FIRST(Fields!ColACaption.Value)
等,所以你不必擔心列名是動態的。 如果您知道您將返回多少列,則此方法有效。
但是如果在SSRS中做到這一點可能更容易。創建一個矩陣,將列組設置爲一個返回ProcessDate列YEAR的表達式,然後在每個值類型的詳細組中添加一行(OpExp,Tax & Total),並且應該給你想要的東西也無需更改任何SQL。
感謝您的建議。這是第一次在SSRS和谷歌工作,找到一個很好的鏈接,將列轉置爲使用表的SSRS中的行。 https://jl45sql.wordpress.com/2012/06/13/transposing-a-dataset-in-ssrs/ –
帶有3行的Tablix會比這更簡單。我將使用您的示例數據做一個快速示例。 –