在自己的表中将行与列连接

时间:2019-03-14 05:30:37

标签: sql

我有一个内部联接后生成的表,就像

加入后的表。

ID_ACC | Model_1 | Model_2 | Model_3 | ACTUAl |  
  1    | m1_val1 | m2_val1 | m3_val1 |  val1  |  
  2    | m1_val2 | m2_val2 | m3_val2 |  val2  |  
  3    | m1_val3 | m2_val3 | m3_val3 |  val3  |  
  4    | m1_val4 | m2_val4 | m3_val4 |  val4  |  
  5    | m1_val5 | m2_val5 | m3_val5 |  val5  |  

我希望此表进行更新并制作新的表,该表应为

必需的表。

ID_ACC | Model   | Value   | ACTUAl |  
  1    | Model_1 | m1_val1 |  val1  |  
  1    | Model_2 | m1_val2 |  val1  |  
  1    | Model_3 | m1_val3 |  val1  |  
  2    | Model_1 | m2_val1 |  val2  |  
  2    | Model_2 | m2_val2 |  val2  |  
  2    | Model_3 | m2_val3 |  val2  |  
  3    | Model_1 | m3_val1 |  val3  |  
  3    | Model_2 | m3_val2 |  val3  |  
  3    | Model_3 | m3_val3 |  val3  |  
  4    | Model_1 | m4_val1 |  val4  |  
  4    | Model_2 | m4_val2 |  val4  |  
  4    | Model_3 | m4_val3 |  val4  |  
  5    | Model_1 | m5_val1 |  val5  |  
  5    | Model_2 | m5_val2 |  val5  |  
  5    | Model_3 | m5_val3 |  val5  |  

那么从上表中获得该结果的查询应该是什么?

2 个答案:

答案 0 :(得分:1)

全部使用联盟

select ID_ACC, 'Model_1' as model,Model_1 as value, actual from tablename
union all
select ID_ACC, 'Model_2' as model,Model_2 as value, actual from tablename
union all
select ID_ACC, 'Model_3' as model,Model_3 as value, actual from tablename

答案 1 :(得分:0)

以下是标准的ANSI SQL:

.custom-styles input[type=checkbox]:checked+label::before {
  border-color: red;
  background-color: red;   
}

在线示例:https://rextester.com/ZHZJR43210


或使用select t.* from models cross join lateral ( values (id_acc, model_1, 'Model 1', actual), (id_acc, model_2, 'Model 2', actual), (id_acc, model_3, 'Model 3', actual) ) as t(id_acc, value, model, actual) order by id_acc; 运算符:

UNPIVOT

在线示例:https://dbfiddle.uk/?rdbms=oracle_18&fiddle=e270ddae4449127a64a345f0066832e6