且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 2005,将列变成行

更新时间:2023-02-07 13:36:14

这个答案真的是frantisek的,我只是复制到这里纠正错误(不能直接编辑).

基本上,您可以使用该解决方案,但需要稍作调整:

选择最大值(DE)为 DE,最大值(EN)为 EN从测试PIVOT (MAX([text]) FOR ISO in (DE,EN)) p

这会将内容放在一行中.此外,它会删除 ID,因为如果您想要单行,它没有意义(没有逻辑来指示在组合成单行时如何处理它).

此外,假设 ISO 列中的值是唯一的,否则,这将由于 MAX 聚合.

I am trying to turn a table 90 degrees: make columns rows. No PIVOT is allowed since PIVOT requires aggregate functions.

Example: I have a table with the columns:
ID int,
ISO char(2),
Text varchar(255).

So I have this:

ID ISO Text
-- --- ----
 1 DE  Auto
 2 EN  Car

I'd like to get the following:

ID EN  DE
-- --- ----
 1 Car Auto

How do you accomplish that?

This answer is really frantisek's, I'm just copying here to correct the mistake (I can't edit directly).

Basically, you use that solution, with a tweak:

SELECT 
    max(DE) as DE, max(EN) as EN 
FROM 
    test 
PIVOT (MAX([text]) FOR ISO in (DE,EN)) p

This will get the content into a single row. Also, it drops the ID, since it doesn't make sense if you want a single row (there is no logic to indicate what to do with it when combining into a single row).

Also, the assumption is made that the values in the ISO column are unique, otherwise, this will lose data due to the MAX aggregate.