【问题标题】:Convert columns to rows Teradata将列转换为行 Teradata
【发布时间】:2017-08-09 07:50:19
【问题描述】:

我需要在没有 TD_UNPIVOT 的情况下将 Teradata 中的列转换为行。我的桌子

ID |Code_1 | Code_2 | Code_3 | Code_4| 1 |1000 | 2000 | 3000 | 4000 | 1 |1000 | 2000 | 3000 | NULL | 1 |1000 | 2000 | NULL | NULL | 1 |1000 | NULL | NULL | NULL |

我需要将 Code_1、Code_2、Code_3、Code_4 转换为 2 列:第一列将包含所有 Code_n(不带 NULL),第二列将具有代码级别:

ID | Code_n | Level_of_Code
1  | 4000   | 4
1  | 3000   | 3
1  | 2000   | 2
1  | 1000   | 1

这意味着,我应该知道 Code 何时为 NULL(在 Code_1、Code_2、Code_3 或 Code_4 的哪个级别,然后将其转换为我没有为 NULL 的最大级别数的列)。

请帮助我。 谢谢

【问题讨论】:

  • 我无法使用 td_unpivot,我无权激活它
  • 呃,那你需要使用UNIONSELECT ID, code_1, 1 as level_of_code from <your table> union select id,code_2 from <your table>... order by 1, 3 desc.
  • 谢谢,Level_of_Code 我可以在 case 语句中添加:select id, code_1 as code, case when code_1 is not null then '1' end as Lefel_of_Code from <table> where code is not NULL,是吗?
  • 在 case 语句和 where 子句中这样做是多余的,但它会起作用,是的。

标签: teradata


【解决方案1】:

您可以通过使用多个 select 语句并执行 union all 以将它们连接在一起来生成行。

Select id, code_1 as "code_n", 1 as "level_of_code" from your table
Union all
Select id, code_2,2
Union all
Select id, code_3,3
Union all
 Select id, code_4,4;

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 2021-09-15
    • 2018-12-21
    • 2015-12-19
    • 1970-01-01
    • 2015-09-02
    • 2017-11-24
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多