Hi to all. I need to rewrite the code below ideally as a View as calling application is unable to pass a parameter.The requirement:When the view is executed it should return data for the current 'AccountingYear' + previous 'AccountingPeriod' (values defined in table AccountingCalendar).IF 'AccountingPeriod' = 1 then it should return data from previous 'AccountingYear' + last 'AccountingPeriod' i.e. 12.I hope that makes some sense. The SQL code is below. I have attached script to create tables, insert test data + run the query (all done in SQL 2014).[quote]--Query DECLARE @Year int DECLARE @Period int SET @Year = 2015 --(SELECT AccountingYear FROM AccountingCalendar WHERE AccountingDate = convert(varchar(20),getdate(),106)) SET @Period = 12 --(SELECT AccountingPeriod FROM AccountingCalendar WHERE AccountingDate = convert(varchar(20),getdate(),106)) SELECT MAX(GLChartOfAccounts.GLChartOfAccountId) AS GLChartOfAccountId, SUM(DTbl.OpenBalance) AS OpenBalance, SUM(DTbl.ThisPeriodDebits) AS ThisPeriodDebits, SUM(DTbl.ThisPeriodCredits) AS ThisPeriodCredits, SUM(DTbl.GLItemValue) AS ClosingBalance FROM ( SELECT GLItems.GLChartOfAccount, SUM(GLItems.GLItemValue) AS GLItemValue, SUM(GLItems.GLItemValue) AS OpenBalance, NULL AS ThisPeriodCredits, NULL AS ThisPeriodDebits FROM GLItems LEFT OUTER JOIN GLChartOfAccounts ON GLItems.GLChartOfAccount = GLChartOfAccounts.GLChartOfAccount WHERE GLItems.GLYearPeriod < ((@Year*100)+@Period) AND NOT(GLItems.SourceType = 'YC' AND round(GLItems.GLYearPeriod,-2) / 100 = @Year) GROUP BY GLItems.GLChartOfAccount UNION ALL SELECT GLItems.GLChartOfAccount, SUM(GLItems.GLItemValue), SUM(CASE WHEN GLItems.SourceType = 'YO' THEN GLItems.GLItemValue ELSE NULL END), SUM(CASE WHEN GLItems.SourceType = 'YO' THEN NULL WHEN GLItems.GLItemValue < 0 THEN GLItems.GLItemValue ELSE NULL END), SUM(CASE WHEN GLItems.SourceType = 'YO' THEN NULL WHEN GLItems.GLItemValue >= 0 THEN GLItems.GLItemValue ELSE NULL END) FROM GLItems LEFT OUTER JOIN GLChartOfAccounts ON GLItems.GLChartOfAccount = GLChartOfAccounts.GLChartOfAccount WHERE GLItems.GLYearPeriod = ((@Year*100)+@Period) AND NOT(GLItems.SourceType = 'YC' AND round(GLItems.GLYearPeriod,-2) / 100 = @Year) GROUP BY GLItems.GLChartOfAccount ) AS DTbl LEFT OUTER JOIN GLChartOfAccounts ON DTbl.GLChartOfAccount = GLChartOfAccounts.GLChartOfAccount GROUP BY DTbl.GLChartOfAccount HAVING NOT (ISNULL(SUM(DTbl.ThisPeriodCredits),0) = 0 AND ISNULL(SUM(DTbl.ThisPeriodDebits),0) = 0 AND ISNULL(SUM(DTbl.OpenBalance),0) = 0) ORDER BY GLChartOfAccountId[/quote]Kind Regards,Phil.
↧