【问题标题】:Is there a method to simply transpose a table in SQL. This table contains Numeric and Varchar values有没有一种方法可以简单地转置 SQL 中的表。此表包含 Numeric 和 Varchar 值
【发布时间】:2021-01-15 12:20:01
【问题描述】:

我想知道如何在 SQL 中非常简单地转置一个表。无需进行总和或计算。

此表包含 Numeric 和 Varchar 值。

意思是,我有一个 2 行 x 195 列的表格。我想要一张 195 行 x 2 列(可能是 3 列)的表

time_index legal_entity_code cohort ... ...
0 AAA 50 ... ...
1 BBB 55 ... ...

Element time_index_0 time_index_1
legal_entity_code AAA BBB
cohort 50 55
... ... ...
... ... ...

我已经创建了这段代码用于测试

SELECT  time_index, ValueT, FieldName
FROM   (select legal_entity_code, cohort, time_index from ifrs17.output_bba where id in (1349392,1349034)) as T
UNPIVOT
(
    ValueT
    FOR FieldName in ([legal_entity_code],[cohort])
) as P

但我收到此错误消息:

“cohort”列的类型与 UNPIVOT 列表中指定的其他列的类型冲突。

【问题讨论】:

  • 错误在这里告诉你问题;你不明白错误怎么办,我们可以尝试详细说明。
  • 你的问题和你的代码不一致。这有点难以理解。
  • 确实很抱歉给大家带来了不一致。 Name1 将是“法人实体代码”,Value1 将是“群组”。等等...该表通常包含 195 列。在这段代码中,我只展示了其中的 3 个(为简单起见)

标签: sql sql-server pivot pivot-table unpivot


【解决方案1】:

我建议为此使用apply。我没有完全遵循指定的结果,因为查询和示例数据的命名不一致。

我很确定你想要:

select o.time_index, v.*
from ifrs17.output_bba o cross apply
     (values ('Name1', o.name1),
             ('Value1', convert(varchar(max), o.value1)),
             ('Name2', o.name2)
     ) v(name, value)            
where o.id in (1349392,1349034);

【讨论】:

  • 抱歉,不一致。 Name1 将是“法人实体代码”,Value1 将是“群组”。等等...该表通常包含 195 列。在这段代码中,我只展示了其中的 3 个(为简单起见)
【解决方案2】:

Gordon 的方法是正确的,而且性能肯定更高。 +1

但是,如果您想动态地对 195 列进行反透视,而不必将它们全部列出,请考虑以下事项:

注意:如果不是 2016+ ... 有类似的 XML 方法。

示例或dbFiddle

Select Element = [Key]
      ,Time_Index_0 = max(case when time_index=0 then value end)
      ,Time_Index_1 = max(case when time_index=1 then value end)
 From  (
        Select [time_index]
              ,B.*
         From  YourTable A
         Cross Apply (
                      Select [Key]
                            ,Value
                       From OpenJson( (Select A.* For JSON Path,Without_Array_Wrapper ) ) 
                       Where [Key] not in ('time_index')
                     ) B
        ) A
 Group By [Key]

退货

Element             Time_Index_0    Time_Index_1
cohort              50              55
legal_entity_code   AAA             BBB

【讨论】:

  • 疯了!!非常感谢约翰和其他回复的人!对我很有帮助!!!
  • @Nassim 总是乐于提供帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 2011-02-17
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多