SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Pivot
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Petronas
Posting Yak Master

133 Posts

Posted - 12/06/2013 :  14:26:53  Show Profile  Reply with Quote
Hi,

I have a following table:
Customer Id Billing Amt Bill Sent Mnth Bill sent date
100391 86.55 201302 2/18/2013
100391 79.95 201304 4/8/2013
100391 65.75 201305 5/13/2013
72331 15.95 201301 1/12/2013
72331 24.95 201303 3/3/2013

I need to display is as

Customer ID 201301 201302 201303 201304 201305 201306 201307
100391 2/8/2013 4/8/2013 5/13/2013
72331 1/12/2013 3/3/2013

I have to put the Bill Sent Mnths as Columns and have the Bill sent date for each corresponding customer_id displayed under it.

Thank you ,
Petronas

visakh16
Very Important crosS Applying yaK Herder

India
52249 Posts

Posted - 12/07/2013 :  04:12:50  Show Profile  Reply with Quote

DECLARE @BillMonthList varchar(5000),@SQLQuery varchar(max)

SELECT @BillMonthList = STUFF((SELECT DISTINCT ',[' + CAST([Bill Sent Mnth] AS varchar(6)) + ']' FROM Table ORDER BY ',[' + CAST([Bill Sent Mnth] AS varchar(6)) + ']' FOR XML PATH('')),1,1,'')

SET @SQLQuery='SELECT Customer_ID,' + @BillMonthList +
' FROM
(
SELECT t.*,t1.[Bill sent date]
FROM
(
SELECT m.BillMonth,n.Customer_ID
FROM (SELECT DISTINCT [Bill Sent Mnth] AS BillMonth FROM Table)m
CROSS JOIN (SELECT DISTINCT Customer_ID FROM Table)n
)t
LEFT JOIN Table t1
ON t1.[Bill Sent Mnth] = t.BillMonth 
AND t1.Customer_ID = t.Customer_ID 
)o
PIVOT (MAX([Bill sent date]) FOR BillMonth IN (' + @BillMonthList + '))p'

EXEC (@SQLQuery)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000