[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 376
  • Last Modified:

Simple Pivot Question

have a query (select  [AcctNo], [shares], [symbol] from MyTable) that returns:

[AcctNo], [shares], [symbol]
acct01,    100 ,  msft
acct02,    150,  msft
acct02,    200,  aapl
acct02,    250 ,  aapl
acct03,    300 ,  intl
.
..

I'd like to pivot the data so it displays as:
[ ] ,    [acct01] , [acct02], [acct03], .....
msft,        100,         150,      0
aapl,             0,         450,     0
intl ,              0,             0,     300
.
..
Number of [AcctNo] and [symbol] are undetermined.

Any help on the SQL here would be appreciated.
0
chrisli
Asked:
chrisli
1 Solution
 
tim_csCommented:
DECLARE @Table TABLE (AcctNo VARCHAR(20),shares INT, symbol VARCHAR(20))

INSERT INTO @Table
        (AcctNo, shares, symbol)
VALUES
        ('acct01',100,'msft')
		,('acct02',150,'msft')
		,('acct02',200,'aapl')
		,('acct02',250,'aapl')
		,('acct03',300,'intl')

SELECT
	symbol
	,COALESCE([acct01],0) Acct01
	,COALESCE([acct02],0) Acct02
	,COALESCE([acct03],0) Acct03
FROM
	@Table
PIVOT (SUM(shares) FOR AcctNo IN ([acct01]
	,[acct02]
	,[acct03])) pvt

Open in new window

0
 
chrisliAuthor Commented:
Thanks, but what if the # of acctno is not dynamic(more than 3)?
0
 
appariCommented:
try this
DECLARE @accounts VARCHAR(max)
;with accounts as (Select distinct AcctNo From MyTable)
Select @accounts = COALESCE( '[' + AcctNo + '],' + @accounts,'[' + AcctNo + ']') from accounts 

Exec('Select symbol,' + @accounts + ' From  MyTable PIVOT (Sum(shares) for AcctNo in (' + @accounts + ')) as PVT ')

Open in new window

0
 
BuggyCoderCommented:
See this for your reference, a very good discussion on problem that you have...
http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SQL_Server_2008/Q_27633177.html#a37724982
0
 
chrisliAuthor Commented:
Thanks works great
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now