Reputation: 125
Here's my query ,
DECLARE @BranchAsColumn nvarchar(max)
-- it may contain branchesName sepereated by comma(,) using as dynamic column, and it may vary e.g. #ABC,#LMN,#XYZ
DECLARE @Branches nvarchar(max)
-- it may contain branchesName sepereated by comma(,) using for filter condition, and it may vary e.g. ABC,LMN,XYZ
EXEC('Select CompanyID,Company,Category,SubCategory,Months,'+@BranchAsColumn+'
From
( Select
BranchID,
Branch,
CompanyID,
Company,
Months,
Department,
Amount
From #Data
)P
PIVOT
(
SUM(Amount)
For Branch in ('+@Branches +')
) As Pivottable')
What ever result I will get here I just wanted to insert retrieved data into Another TABLE, so please anyone here help me to get the perfect solution.
Upvotes: 1
Views: 1999
Reputation: 30052
Try this out:
EXEC('Select CompanyID,Company,Category,SubCategory,Months,'+@BranchAsColumn+'
INTO ##MyTable
From ( Select
BranchID, Branch,
CompanyID,
Company,
Months, Department,
Amount
From #Data )P PIVOT ( SUM(Amount) For Branch in ('+@Branches +') ) As Pivottable')
-- test results
SELECT * FROM ##MyTable
Upvotes: 2