[英]SQL Can I have one result table from two queries so they align data in different columns
[英]I have several columns from different tables I need to combine into one so that they are separate rows in the result
資料范例
表格1
Value component1
1 456
表2
Value component2
1 555A
表3
value component3
2 356
輸出我得到
Value component1 component2 component3
1 456 555A
2 356
我想要的輸出-單獨的行
Value component
1 456
1 555A
2 356
您可以這樣使用union:
SELECT * FROM TableA
UNION
SELECT * FROM TableB
UNION
SELECT * FROM TableC
UNION
SELECT * FROM TableD
如果需要更多信息,請參考此頁面: use union
您可以使用UNION ALL並使別名與每個表上的參數相同。 請看下面:
SELECT `value`,`component1` as 'component' FROM `table1`
UNION ALL
SELECT `value`,`component2` as 'component' FROM `table2`
UNION ALL
SELECT `value`,`component3` as 'component' FROM `table3`
您需要在要合並的每個表上設置相同的表達式/別名。 如果您想了解更多關於MySQL Union和Union All Operators Primer的信息,請參考此鏈接。
with cte as
(
Select value from table1
union
Select value from table2
union
Select value from table3
)
select cte.value
, table1.Value as component1
, table2.Value as component2
, table3.Value as component3
from cte
left outer join table1 on table1.value = cte.value
left outer join table2 on table2.value = cte.value
left outer join table3 on table3.value = cte.value
關於您到目前為止所說的內容,TO_CHAR可能會有所幫助。
SQL> create table table1 (value number, component1 number);
Table created.
SQL> create table table2 (value number, component2 varchar2(20));
Table created.
SQL> create table table3 (value number, component3 number);
Table created.
SQL> insert all
2 into table1 values (1, 456)
3 into table2 values (1, '555A')
4 into table3 values (2, 356)
5 select * From dual;
3 rows created.
SQL>
SQL> select t1.value, to_char(t1.component1) component from table1 t1 union
2 select t2.value, t2.component2 from table2 t2 union
3 select t3.value, to_char(t3.component3) from table3 t3;
VALUE COMPONENT
---------- ----------------------------------------
1 456
1 555A
2 356
SQL>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.