有没有一种方法可以简单地在 SQL 中转置 table。此 table 包含数字和 Varchar 值

Is there a method to simply transpose a table in SQL. This table contains Numeric and Varchar values

我想知道如何在 SQL 中非常简单地转置 table。没有求和或计算。

此 table 包含数值和 Varchar 值。

意思是,我有一个 2 行 x 195 列的 table。我想要相同的 table 和 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

但我收到此错误消息:

The type of column "cohort" conflicts with the type of other columns specified in the UNPIVOT list.

我建议为此使用 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);

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]

Returns

Element             Time_Index_0    Time_Index_1
cohort              50              55
legal_entity_code   AAA             BBB