Link to home
Start Free TrialLog in
Avatar of RETAILREALM
RETAILREALMFlag for United States of America

asked on

Sql row to column

I have two columns as shown below

ColA       ColB
Cash      100
Check     200
Card       300

I want result as

Cash    Check  Card
100      200      300


Here colA has run time values so i can't make it hard code



SOLUTION
Avatar of Patrick Matthews
Patrick Matthews
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Note: PIVOT works for SQL 2005 and above; Matthew's approach works on SQL 2000 as well.  The only thing I would change is one first occurrence you want to check if NULL.
SELECT @sql = IsNull(@sql + ',', '') + '(SELECT SUM(ColB) FROM SomeTable WHERE ColA = ''' + ColA + ''') AS [' + ColA + ']'
FROM SomeTable
GROUP BY ColA
ORDER BY ColA

Open in new window

Avatar of RETAILREALM

ASKER

Thanks guys for your help