我有下一个表结构:
需要下一种格式的数据:
但结果如下:
我的代码:
SELECT * FROM (
SELECT
record,
field AS real_field,
real_value,
field AS string_field,
string_value
FROM my_table ) AS source
PIVOT ( MAX(string_value) FOR string_field IN ([1],[2],[3],[4]) ) AS string_pivot
PIVOT ( MAX(real_value) FOR real_field IN ([5],[6]) ) AS real_pivot;
有什么想法吗?谢谢。
答案 0 :(得分:0)
你可以简单地使用coalesce,不是吗?
DECLARE @test TABLE(record INT,
field INT,
real_value DECIMAL NULL,
string_value VARCHAR(10) NULL);
INSERT INTO @test(record, field, real_value, string_value)
VALUES(1, 1, NULL, 'A'),
(1, 2, NULL, 'B'),
(1, 3, NULL, 'C'),
(1, 4, NULL, 'D'),
(1, 5, 1.0, NULL),
(1, 6, 2.0, NULL);
SELECT *
FROM(
SELECT record, field, COALESCE(CONVERT(VARCHAR(10), real_value, 0), string_value) AS value
FROM @test
) AS source
PIVOT(MAX(value)
FOR field IN([1], [2], [3], [4], [5], [6])
) AS real_pivot;
答案 1 :(得分:0)
嗯,它实际上比我想象的更简单:
SELECT record, MAX([1]), MAX([2]), MAX([3]), MAX([4]), MAX([5]), MAX([6]) FROM ( SELECT record, field AS real_field, real_value, field AS string_field, string_value FROM my_table ) AS source
PIVOT ( MAX(string_value) FOR string_field IN ([1],[2],[3],[4]) ) AS string_pivot
PIVOT ( MAX(real_value) FOR real_field IN ([5],[6]) ) AS real_pivot
GROUP BY record;