如何在SQL中合并列并进行转置?

huangapple go评论94阅读模式
英文:

How to merge columns and transpose in SQL?

问题

我正在使用自定义的DBMS(符合SQL 2011标准),尝试将多个列合并为单个列,如下所示,但在语法方面遇到了困难:

当前表格:

  1. ------------------------------------------
  2. | ID | setting_A | setting_B | setting_C |
  3. ------------------------------------------
  4. | 1 | ON | OFF | UNKNOWN |
  5. ------------------------------------------

期望的查询结果:

  1. ------------------------------
  2. | ID | Setting | Value |
  3. ------------------------------
  4. | 1 | A | ON |
  5. ------------------------------
  6. | 1 | B | OFF |
  7. ------------------------------
  8. | 1 | C | UNKNOWN |
  9. ------------------------------

我已经尝试了各种IF和CASE语句,但遇到了难题。任何帮助将不胜感激。

英文:

I'm working with a custom DBMS (compliant with SQL 2011 Standard), and am trying to combine multiple columns into a single column like so, but am struggling with the syntax:

Current table:

  1. ------------------------------------------
  2. | ID | setting_A | setting_B | setting_C |
  3. ------------------------------------------
  4. | 1 | ON | OFF | UNKNOWN |
  5. ------------------------------------------

Desired query output:

  1. ------------------------------
  2. | ID | Setting | Value |
  3. ------------------------------
  4. | 1 | A | ON |
  5. ------------------------------
  6. | 1 | B | OFF |
  7. ------------------------------
  8. | 1 | C | UNKNOWN |
  9. ------------------------------

I've tried various IF and CASE statements, but have hit a wall. Any help would be appreciated.

答案1

得分: 1

你可以使用 union all 进行解旋(unpivot)

  1. select id, 'A' setting, setting_A value from mytable
  2. union all select id, 'B', setting_B from mytable
  3. union all select id, 'C', setting_C from mytable

这假设 setting_Asetting_Bsetting_C 具有相同的数据类型(否则,在组合结果集之前,您需要进行数据类型转换以使其一致)。

英文:

You can unpivot with union all:

  1. select id, 'A' setting, setting_A value from mytable
  2. union all select id, 'B', setting_B from mytable
  3. union all select id, 'C', setting_C from mytable

This assumes that setting_A, setting_B and setting_C are of the same datatype (otherwise, you need conversions to align the datatypes before combining the resultsets).

Demo on DB Fiddle:

<pre>

id setting value
1 A ON
1 B OFF
1 C UNKNOWN
</pre>

huangapple
  • 本文由 发表于 2020年1月7日 00:34:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定