逐行显示

时间:2011-10-24 08:53:49

标签: sql sql-server

使用SQL Server 2000

表1

ID Value

101 100
102 200
103 500

表格中只有3行。我想以行方式进行视图

预期产出

101 102 103
100 200 500

如何针对上述情况进行选择查询。

需要查询帮助

2 个答案:

答案 0 :(得分:1)

如果您确定知道ID列中的值,可以使用以下查询:

SELECT
    MAX(id_101) AS id_101,
    MAX(id_102) AS id_102,
    MAX(id_103) AS id_103
FROM (
SELECT
    1 AS aux,
    CASE WHEN ID = 101 THEN val ELSE null END AS id_101,
    CASE WHEN ID = 102 THEN val ELSE null END AS id_102,
    CASE WHEN ID = 103 THEN val ELSE null END AS id_103
FROM table1
) AS t(aux, id_101, id_102, id_103)
GROUP BY t.aux;

答案 1 :(得分:1)

假设101,102,103是列名,您可以使用PIVOT旋转表:

SELECT *
FROM 
(
 SELECT id, value
 FROM @data1
) p
PIVOT (SUM(value) FOR [id] IN ([101], [102], [103])) AS pvt

enter image description here


准备数据:

DECLARE @data1 TABLE(id int, value INT)
INSERT INTO @data1 VALUES(101, 100)
INSERT INTO @data1 VALUES(102, 200)
INSERT INTO @data1 VALUES(103, 500)