Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have 2 tables (Account Tree , Dialy Records)

Account tree (Code,Account Name)

Daily Records (Date,<code,account>
I want to show this

Month     Code   Account Credit Debit
---------------------------------------------------------
Jan
Feb
Mar
ETC..
Posted
Updated 24-Nov-15 10:42am
v2
Comments
phil.o 24-Nov-15 16:20pm    
That's not a question. What have you tried?

1 solution

Assuming you have a table defined as such

CREATE TABLE [dbo].[testpivot](<br />
	[Month] [varchar](50) NOT NULL,<br />
	[Sales] [money] NOT NULL,<br />
	[InsertDate] [date] NULL<br />
) ON [PRIMARY]


and you have the following rows:

Month Sales InsertDate
Jan 20.00 2015-01-01
Feb 15.00 2015-01-01
Mar 18.00 2015-01-01
Apr 19.00 2015-01-01
May 14.00 2015-01-01
Jun 21.00 2015-01-01

You can pivot for the following:

JanSales, FebSales,MarSales,AprSales
20.00, 15.00, 18.00, 19.00

Using the following two methods.

1. Self Joins

SQL
select j.Sales as JanSales, f.Sales as FebSales, m.Sales as MarchSales, a.Sales as AprilSales from dbo.testpivot j
join dbo.testpivot f on f.InsertDate = j.InsertDate and f.[Month] = 'Feb'
join dbo.testpivot m on m.InsertDate = j.InsertDate and m.[Month] = 'Mar'
join dbo.testpivot a on a.InsertDate = j.InsertDate and a.[Month] = 'Apr'
 where j.[MONTH] = 'Jan' 



2. Pivot Key word.

SQL
select Jan as JanSales, Feb as FebSales, Mar as MarchSales, Apr as AprilSales
	from  dbo.testpivot
	pivot 
	( 
		max(Sales)
	
		for [Month] IN (Jan, Feb, Mar, Apr)

	) as pvt
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900