Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 join on two dynamic SQL statements ...

Author  Topic 

vamsimahi
Starting Member

29 Posts

Posted - 2008-08-22 : 11:30:44
Hi,

I have two tables table1 and Table2.
Columns in Table1 are [CustomerID], [Product], [ProductShare]
Columns in Table2 are [CustomerID], [Product], [ProductChange]

I am using a dynamic pivot to convert the different products in [Product] column as different columns. I am doing this for both my Tables. Below is the code:

-- This code I got from BOL for selecting the different products in [Product] column into a string

DECLARE @cols VARCHAR(MAX)
SET @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
'],[' + A.Product
FROM dbo.Table1 AS A
ORDER BY '],[' + A.Product
FOR XML PATH('')
), 1, 2, '') + ']'
---------------------------------
Similarly, I am getting different products in Table2 into @cols1
--------------------------------

--This is code for Pivot which converts my products into Different columns for Table1

'SELECT CustomerID, '+
@cols +' FROM (SELECT A.CustomerID, A.Product, A.ProductShare
FROM dbo.Table1 AS A) P
PIVOT
(
SUM([ProductShare])
FOR Product IN( '+ @cols +' )) X'
-------------------------------------
Similarly, I am doing this for Table2
-------------------------------------

Now, I want to get the CustomerID, columns in Pivot1 (for @cols) and columns in Pivot2(for @cols1). I want to do a inner join my CustomerID.
Can someone help me with a query.....

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2008-08-25 : 04:47:30
Hi vamsimahi

You'd probably be better off posting a sample table structure for the tables involved, some sample data and just show how you need the result to look.

If you can provide that, then someone will give you a solution quickly.

Regards,

-------------
Charlie
Go to Top of Page
   

- Advertisement -