美文网首页
SQL-Pivot on AX ledger balance

SQL-Pivot on AX ledger balance

作者: axxxxxxxx | 来源:发表于2018-09-21 16:16 被阅读0次

http://sharedderrick.blogspot.com/2013/02/pivot-dynamic-pivot.html

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)
declare @fromDate datetime

set @fromDate = '2017-4-1'
drop table if exists #TempTable

select * into #TempTable from 
(SELECT  LEFT(CONVERT(VARCHAR, e.ACCOUNTINGDATE, 120), 7)  as TransDate, e.SUBLEDGERVOUCHERDATAAREAID as company, m.MAINACCOUNTID as ID,  
(a.ACCOUNTINGCURRENCYAMOUNT)AS BL
  FROM GENERALJOURNALACCOUNTENTRY a
  JOIN GENERALJOURNALENTRY e  ON e.[PARTITION] = a.[PARTITION] AND e.RECID = a.GENERALJOURNALENTRY
  JOIN MAINACCOUNT m          ON m.[PARTITION] = a.[PARTITION] AND m.RECID = a.MAINACCOUNT
  JOIN FISCALCALENDARPERIOD p ON p.[PARTITION] = e.[PARTITION] AND p.RECID = e.FISCALCALENDARPERIOD
  WHERE p.type =  1-- 0=Opening,1=Operating,2=Closing
 and e.accountingdate >= @FromDate and e.accountingdate < dateadd(month,12,@FromDate) 
 )AS A

--select * from #TempTable
 
SELECT @cols = COALESCE(@cols + ',' ,'' ) + QUOTENAME(TransDate) 
FROM #TempTable 
GROUP BY QUOTENAME(TransDate) 
Order by QUOTENAME(TransDate) 

SELECT @query  = N'
SELECT * FROM #TempTable  PIVOT (SUM(BL) FOR TransDate 
 IN (' + @cols +  N') ) AS pvt order by company'

EXEC sp_executesql @query;
drop table if exists #TempTable

相关文章

网友评论

      本文标题:SQL-Pivot on AX ledger balance

      本文链接:https://www.haomeiwen.com/subject/fvfznftx.html