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

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

How to merge columns and transpose in SQL?

问题

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

当前表格:

------------------------------------------
| ID | setting_A | setting_B | setting_C |
------------------------------------------
| 1  |     ON    |    OFF    |  UNKNOWN  |
------------------------------------------

期望的查询结果:

------------------------------
|  ID  |  Setting  |  Value  |
------------------------------
|  1   |     A     |    ON   |
------------------------------
|  1   |     B     |   OFF   |
------------------------------
|  1   |     C     | UNKNOWN |
------------------------------

我已经尝试了各种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:

------------------------------------------
| ID | setting_A | setting_B | setting_C |
------------------------------------------
| 1  |     ON    |    OFF    |  UNKNOWN  |
------------------------------------------

Desired query output:

------------------------------
|  ID  |  Setting  |  Value  |
------------------------------
|  1   |     A     |    ON   |
------------------------------
|  1   |     B     |   OFF   |
------------------------------
|  1   |     C     | UNKNOWN |
------------------------------

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

答案1

得分: 1

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

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

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

英文:

You can unpivot with union all:

select id, 'A' setting, setting_A value from mytable
union all select id, 'B', setting_B from mytable
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:

确定