将列值转换为行值

时间:2020-09-14 04:30:14

标签: sql sql-server database pivot

在SQL Server中,我试图将表1转换为表2。从读取堆栈溢出的其他答案后,我可以执行某种row_number()。但是问题是,转换后我需要进行一些内部联接,因为以下脚本使用max()聚合函数,它会强制其他表中的其他字段也具有某种聚合函数。所以我想知道是否存在替代方法来解决此问题?或者,如果有一种方法可以在与另一个表联接时处理此聚合函数。

select max(case when key = 'ab' then Value end) as ab, 
       max(case when key = 'cd' then Value end) as cd
from (select t.*, 
             row_number() over (partition by key order by Value) as seq
      from table t
     ) t
group by seq;

表1

enter image description here

表2

enter image description here

2 个答案:

答案 0 :(得分:4)

您可以在下面的脚本中尝试此操作-

SELECT id,
MAX(CASE WHEN name = 'car1' THEN name END) car1,
MAX(CASE WHEN name = 'car2' THEN name END) car2, 
MAX(CASE WHEN name = 'car3' THEN name END) car3 
FROM your_table
GROUP BY id

答案 1 :(得分:1)

您可以使用PIVOT功能。

;WITH src as
(
    SELECT *
    FROM
    (
        VALUES
        (1, 'Car1', 'nissan'),
        (1, 'Car2', 'audi'),
        (1, 'Car3', 'toyota')
    ) as t (id, name, value)
)
SELECT *
FROM src
PIVOT
(
    max(VALUE) FOR NAME IN ([Car1], [Car2], [Car3])
) as pvt

+----+--------+------+--------+
| id |  Car1  | Car2 |  Car3  |
+----+--------+------+--------+
|  1 | nissan | audi | toyota |
+----+--------+------+--------+

相关问题