sql - Transposing a column values into column headers -
i have table this:
+-------------+-----------+------------+ | sample_name | test_name | test_value | +-------------+-----------+------------+ | s1 | t1 | 1.5 | | s2 | t2 | 3 | | s3 | t1 | 8 | | s4 | t3 | 5 | +-------------+-----------+------------+
and want put test_names column headers this
+-------------+------+------+------+ | sample_name | t1 | t2 | t3 | +-------------+------+------+------+ | s1 | 1.5 | null | null | | s2 | null | 3 | null | | s3 | 8 | null | null | | s4 | null | null | 5 | +-------------+------+------+------+
i have come convoluted solution using temporary table, dynamic sql , while loops slow , know, there way select?
thanks
if there values test_name
may use pivot within dynamic sql:
declare @names varchar(max) select @names = coalesce(@names + ', ', '') + test_name (select distinct test_name tbl) t exec(' select * tbl t pivot (sum(test_value) test_name in ('+@names+'))p')
Comments
Post a Comment