Friday, 18 November 2011

Pivot example

DECLARE @listCol VARCHAR(2000)
DECLARE @query VARCHAR(4000)
SELECT  @listCol = STUFF(( SELECT DISTINCT
                                '],[' + ltrim(str(YEAR(transactiondate)))
                        FROM   TblBillingTransaction
                        ORDER BY '],[' + ltrim(str(YEAR(transactiondate)))
                        FOR XML PATH('')
                                    ), 1, 2, '') + ']'
print @listCol
SET @query =

'select * from(select scanamount, datepart(m,transactiondate) as Month ,year(transactiondate) as transactiondate  from TblBillingTransaction where Obsolete=0 and BillingId!=0)as v
pivot (sum(scanamount) for transactiondate
in('+@listCol+') ) as PVT order by 1 asc'


EXECUTE (@query)

RESULT

Month20102011
116780008983115
2461200011186996
3569980010595608
459600009839065
562640109913435
6759139511367465
7923936012233055
8781487011166010
9853212511613364
10883159012208845
1189287007786655
1210024105NULL






No comments:

Post a Comment