Это называется
PIVOT
. Делал
недавно.
Для вас:
DECLARE @UserInfo TABLE ( user_id INT, meta_key VARCHAR(100), meta_value VARCHAR(100) )
INSERT @UserInfo VALUES ( 1, 'gender', 'male' ),
( 1, 'age', '21' ),
( 2, 'gender', 'female' ),
( 2, 'age', '23' ),
( 3, 'gender', 'genderqueer' ),
( 4, 'age', '25' ),
( 4, 'location', 'toster' ),
( 5, 'gender', 'male' ),
( 5, 'age', '27' ),
( 6, 'gender', 'female' ),
( 6, 'age', '29' )
SELECT user_id, gender, age, location
FROM ( SELECT * FROM @UserInfo ) AS UI
PIVOT ( MAX( meta_value ) FOR meta_key IN (gender, age, location )) AS PT
WHERE user_id BETWEEN 2 AND 5
ORDER BY user_id
Результат:
user_id gender age location
2 female 23 NULL
3 genderqueer NULL NULL
4 NULL 25 toster
5 male 27 NULL