我正在尝试制定SSRS报告。我从事务表中获取了销售值,并按年,月和子类别对其进行了分组。我已将其创建为视图。这是视图代码:
SELECT b.FiscalYear AS Year,
b.FiscalMonth AS Month,
a.SubCategoryKey,
MAX(a.SubCategoryDesc) AS SubCategoryDesc,
SUM(CAST(a.Cost + a.FreightCost AS decimal(18, 2))) AS TotalCost,
SUM(CAST(a.SalesAmount AS decimal(18, 2))) AS TotalSales,
SUM(CAST(a.Weight AS decimal(18, 2))) AS Pounds, SUM(CAST(a.SalesAmount -(a.Cost + a.FreightCost) AS decimal(18, 2))) AS Margin
FROM dbo.GrossMargin_CorrectedCosts AS a
LEFT OUTER JOIN dbo.M_DateDim AS b ON a.InvoiceDate = b.Date
GROUP BY b.FiscalYear, b.FiscalMonth, a.SubCategoryKey
然后我留下一个看起来像这样的干净视图:
SELECT [Year]
,[Month]
,[SubCategoryKey]
,[SubCategoryDesc]
,[TotalCost]
,[TotalSales]
,[Pounds]
,[Margin]
FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V]\
我现在想在此查询中添加其他列。我将把它作为SSRS报告运行并传递Year和Month参数。我想做的是当2017年被选为年度参数时,我想显示上一年的TotalSales,TotalCost和Pounds值。
而查询看起来像这样:
SELECT [Year]
,[Month]
,[SubCategoryKey]
,[SubCategoryDesc]
,[TotalCost]
,[TotalSales]
,[Pounds]
,[Margin]
,PreviousYearTotalSales
,PreviousYearTotalCost
,PreviousYearPounds
FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V]
基本上,当一年和一个月传递给报告时,我想显示前一年的总数,总成本和相应期间的英镑减去一年。我有点时间这样做。
我觉得我已经尝试了一切,但显然没有。请帮忙。
答案 0 :(得分:2)
现在您可以使用的视图是以下查询。
SELECT CY.[Year]
,CY.[Month]
,CY.[SubCategoryKey]
,CY.[SubCategoryDesc]
,CY.[TotalCost]
,CY.[TotalSales]
,CY.[Pounds]
,CY.[Margin]
,PY.[TotalSales] AS PreviousYearTotalSales
,PY.[TotalCost] AS PreviousYearTotalCost
,PY.[Pounds] AS PreviousYearPounds
FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V] CY LEFT JOIN [FinancialData].[dbo].[SubCategorySalesbyMonth_V] PY
ON CY.[Year] - 1 = PY.[Year]
AND CY.[Month] = PY.[Month]
AND CY.[SubCategoryKey] = PY.[SubCategoryKey]
AND CY.[Month] = PY.[Month]
这只是一个简单的自我左联合到同一个视图,但从当年(CY)的年份加入到上一年(PY),年 - 1.它是LEFT JOIN
,因此,如果没有任何上一年/月的数据,则前一年的值将为空。
希望这有帮助。