SQL Server 2005,将列变成行 [英] SQL Server 2005, turn columns into rows

查看:18
本文介绍了SQL Server 2005,将列变成行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将桌子旋转 90 度:使列成为行.不允许 PIVOT,因为 PIVOT 需要聚合函数.

示例:我有一个包含列的表:
ID int,
ISO 字符 (2),
文本 varchar(255).

所以我有这个:

<上一页>ID ISO 文本-- ---- ----1 DE 自动2 CN 汽车

我想得到以下:

<上一页>ID EN DE-- ---- ----1 汽车 汽车

你是怎么做到的?

解决方案

这个答案真的是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.

这篇关于SQL Server 2005,将列变成行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆