February 27, 2004 at 10:13 am
Hello,
I need to build a query the transforms columns data into columns, i didn't figure out a way of doing it wiithout using cursors....
Example:
Source table:
Document User DocType
1 Mike Type1
2 Kevin Type1
3 Kevin Type1
4 Zoe Type2
5 Zoe Type3
Query output:
User Type1 Type2 Type3
Mike 1 0 0
Kevin 2 0 0
Zoe 0 1 1
I would apreciate any ideas.
Thanks
Nuno
February 27, 2004 at 10:25 am
select User
, SuM(Case when DocType ='Type1' then 1 ELSE 0 END) as Type1
, SuM(Case when DocType ='Type2' then 1 ELSE 0 END) as Type2
, SuM(Case when DocType ='Type3' then 1 ELSE 0 END) as Type3
FROM
SourceTable
GROUP By User
* Noel
February 27, 2004 at 10:48 am
Nice!
Thanks noeld for your help.
DocTypes can be added by clients, so I will create a cursor to build a dynamic version of the query you suggested.
Nuno
February 27, 2004 at 11:08 am
You May Not need a Cursor. If All that is dynamic is just the "Types"
then You could:
Declare @STR varchar(8000)
SET @STR ='Select User'
SELECT @STR = @STR + , 'SuM(Case when DocType =''' + strType +''' then 1 ELSE 0 END) as ' + strType
FROM (
SELECT DISTINCT Cast(Type as varchar) as strType
FROM TypeSource
) Q
Set @STR = @STR +' FROM SourceTable GROUP By User '
Exec (@str)
* Noel
February 27, 2004 at 1:16 pm
I really have to visit this forum more often!
Thanks a lot!
February 27, 2004 at 1:20 pm
You're WELCOME
* Noel
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply