是否可以将1个选定的行列精确转置为行

时间:2017-05-02 13:48:40

标签: sql oracle pivot oracle-sqldeveloper transpose

正如标题所说,是否可以将表中的一个选定行转换为列?我正在使用Oracle数据库。例如,我有一个复杂的查询:

SELECT t1.id,
  t1.data1,
  t1.data2,
  t2.data1,
  t2.data2,
  t2.data3,
  subs1.data1,
  subs2.data1,
  subs2.data2
FROM Table1 t1
JOIN Table2 t2
ON t1.id = t2.id
JOIN
  (SELECT st1.id,
    st1.data1
  FROM subTable1 st1
  JOIN subTable2
  ON st1.id             = st2.id
  WHERE st2.data1       > 1
  ) AS subs1 ON subs.id = t2.id
LEFT JOIN
  (SELECT st3.id,
    st4.data1,
    st4.data2
  FROM subTable3 st3
  JOIN subTable4 st4
  ON st3.id = st4.id
  UNION
  SELECT st4.id, st4.data1, st4.data2 FROM subTable4 st4 WHERE st4.data1 = 1
  ) AS subs2.id = t1.id
WHERE t1.id     = 1

查询结果应该跟随,并且始终只是一行:

+--------+-------------+-------------+-------------+-------------+-------------+----------------+----------------+----------------+
| t1.id  |  t1.data1   |  t1.data2   |   t2data1   |  t2.data2   |  t2.data3   |  subs1.data1   |  subs2.data1   |  subs2.data2   |
+--------+-------------+-------------+-------------+-------------+-------------+----------------+----------------+----------------+
| someId | someT1Data1 | someT1Data2 | someT2Data1 | someT2Data2 | someT2Data3 | someSubs1Data1 | someSubs2Data1 | someSubs2Data2 |
+--------+-------------+-------------+-------------+-------------+-------------+----------------+----------------+----------------+

我愿意达到的目标应该是这样的:

+-------------+----------------+
|    col1     |      col2      |
+-------------+----------------+
| t1.id       | someId         |
| t1.data1    | someT1Data1    |
| t1.data2    | someT1Data2    |
| t2data1     | someT2Data1    |
| t2.data2    | someT2Data2    |
| t2.data3    | someT2Data3    |
| subs1.data1 | someSubs1Data1 |
| subs2.data1 | someSubs2Data1 |
| subs2.data2 | someSubs2Data2 |
+-------------+----------------+

注意:输出

中不需要col1

所以问题是: 是否有一些简单的解决方法可以将一个选定的行从表转换为列?我的意思是比使用PIVOT()函数更简单的方法,或者如果没有其他选择,如何在有点复杂的查询(嵌套查询等)上使用PIVOT()?

提前谢谢你。

2 个答案:

答案 0 :(得分:1)

Pivot是该作业的工具,但您也可以通过将查询放在CTE中,然后使用多个union all分别获取列来获得相同的结果:< / p>

with cte as (
    /* your query, with appropriate aliases for columns with same name*/
)
select 't1.id' as col1, cte.id as col2 from cte union all
select 't1.data1', cte.data1 from cte union all
...
select 'subs2.data2', cte.subsdata2 from cte

答案 1 :(得分:1)

在这种情况下,

数据透视将是更好的选择。只需在获得结果的第一部分后使用此查询。

SELECT col1, col2 from @Table
 Unpivot
(Col2 For Col1 IN 
(t1.id,t1.data1,t1.data2,t2.data1,t2.data2,t2.data3,subs1.data1,subs2.data1,subs2.data2)) AS a

如果您遇到任何困难,请告诉我。