I am struggling with getting my matrix layout correct. I have had to use a bit of dynamic SQL to generate the SQL query to produce what I want (I cannot change tables/views etc as not in control of the db). I do have the ability to create #Temp tables though, and thought it might be an option?
It has to be dynamic SQL as the number of rows/columns (and names) change as the chart of accounts change (and this happens almost every month).
Basically it is an intersection matrix showing whether to add or subtract accounts.
The issue I am facing is. The Totals in [Level 3] (Gross Margin, EBITDA,NPBT,NPAT) are not showing the correct "sign".
I have tried looking at Last_Value but couldn't get it to work as I am use a cte, and cannot use a window function within it.
What I need is for the Total lines to show the first non blank value in the same column (which would be above it). All other rows need to stay Null.
I am not worried about SQL injection etc as this is run locally to generate an output used elsewhere. The current counter of 171 will be replaced with a dynamic value.
Current Code
declare @sql8 nvarchar(max) = ';with CTE_tbl as
(Select accountid, [level 3], case when drcr = ''Debit'' Then ''-'' else ''+'' end as val,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum From ('+(@sql+@sql2)+ ') h left join (' +(@sql6+@sql+@sql2+@sql7)+') j on j.[Level 2] = h.[Level 2] left join [Propella].[TGLAcctType] k on k.typeid = h.typeid where accountid NOT LIKE ''Blank%''
)
select [Level 3]'
declare @xx nvarchar(max)
set @xx = '0'
While @counter < 171
BEGIN
SET @sql10 = 'Select @x = (Select [level 3] FROM (Select [level 3],ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum From ('+(@sql+@sql2)+ ')k where [level 3] NOT IN (''Gross Margin'',''EBITDA'',''NPBT'',''NPAT'') ) z where rownum BETWEEN ' +cast(@counter as nvarchar(10)) +' AND ' +cast(@counter as nvarchar(10)) +')'
exec sp_executesql @sql10, N'@x nvarchar(max) out', @xx out
SET @sql9 = @sql9 + ', Max(case when rownum = ' +cast(@counter as nvarchar(10)) +' then [val] when ([Level 3] in (''Gross Margin'',''EBITDA'',''NPBT'',''NPAT'') AND rownum >= '+cast(@counter as nvarchar(10)) +') then [val] end ) as '''+@xx+''''
Set @counter = @counter +1
END
SET @sql9 = @sql9+'
FROM CTE_tbl
group By rownum,[level 3]
Order by rownum'
exec (@sql8+@sql9)
The Gross Margin and EBITDA should show the sign from the first non-blank row in the column.
Any help is much appreciated
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.