Hallo,
I have a table with 3 columns:
table tbl_user_class
===============
user_id (int) PK
class_id (varchar(20)) PK
class_value(varchar(100))
values are like so:
user_id class_id class_value
======================
1 firstname Rogier
1 lastname Doekes
2 firstname Mary
3 lastname Smith
....
I would like to create result set in the following format
user_id firstname lastname
====================
1 Rogier Doekes
2 Mary Smith
.....
How do I accomplish this? I tried using CASE WHEN statements but the best I could come up with was this:
1 Rogier null
1 null Doekes
2 Mary null
2 null Smith
when I did the following t-SQL statement:
select userID,
CASE WHEN classID = 'firstname' THEN classvalue END as 'firstname',
CASE WHEN classID = 'lastname' THEN classvalue END as 'lastname'
FROM tbl_user_class
Thanks for any help,
-Rogier DoekesUSE Northwind
GO
CREATE TABLE myTable99([user_id] int, class_id varchar(15), class_value varchar(15))
GO
INSERT INTO myTable99([user_id], class_id, class_value)
SELECT 1, 'firstname', 'Rogier' UNION ALL
SELECT 1, 'lastname', 'Doekes' UNION ALL
SELECT 2, 'firstname', 'Mary' UNION ALL
SELECT 2, 'lastname', 'Smith' UNION ALL
SELECT 3, 'firstname', 'Brett' UNION ALL
SELECT 4, 'lastname', 'Kaiser'
GO
SELECT a.[user_id], b.FirstName, c.LastName
FROM (SELECT Distinct [User_id] FROM myTable99) AS a
LEFT JOIN (SELECT [user_id], class_value as FirstName FROM myTable99 WHERE class_id = 'firstname') AS b
ON a.[user_id] = b.[user_id]
LEFT JOIN (SELECT [user_id], class_value as LastName FROM myTable99 WHERE class_id = 'lastname') AS c
ON a.[user_id] = c.[user_id]
GO
DROP TABLE myTable99
GO|||that does the job,
Thanks a lot Brett
-Rogier
Wednesday, March 7, 2012
creating pivot table
Labels:
columnstable,
creating,
database,
hallo,
int,
microsoft,
mysql,
oracle,
pivot,
pkclass_id,
pkclass_value,
server,
sql,
table,
tbl_user_classuser_id,
values,
varchar
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment