[英]How to make a template table in SQL that pulls specific columns from other different tables
我有多個包含多列的表,但是對於這個問題,我只有三個表,每個表都有一列:
表格1:
ID | 一個 | 乙 |
---|---|---|
1 | 20 | 14 |
2 | 11 |
表2:
ID | C | D | 乙 |
---|---|---|---|
100 | 14 | 4 | |
101 | 16 | 12 | 19 |
表3:
ID | F |
---|---|
1234 | 6 |
8765 | 11 |
所需的 output:
主表:
ID | 表名 | 列名 | 價值 |
---|---|---|---|
1 | 表格1 | 一個 | 20 |
1 | 表格1 | 乙 | 14 |
2 | 表格1 | 乙 | 11 |
100 | 表2 | C | 14 |
101 | 表2 | C | 16 |
101 | 表2 | D | 12 |
101 | 表2 | 乙 | 19 |
8765 | 表3 | F | 11 |
如您所見,我希望查詢也有一個條件,即僅在列值大於 10 時才選擇插入到主表中。
讓我知道我是否可以在問題中添加任何進一步的信息。
為了清楚起見,您可以使用union
和 CTE 來insert
行
with t as (
select id, 'table1' Tablename, 'col1' ColumnName, col1 as Value
from table1
union all
select id, 'table2', 'col2', col2
from table2
union all
select id, 'table3', 'col3', col3
from table3
)
insert into mainTable (id, tableName, columnName, Value)
select id, tableName, columnName, Value
from t
where value > 10
您想創建一個所謂的鍵/值表。 與他們一起工作通常很麻煩,但你會有你的理由。 從普通表到鍵/值表的查詢是按值對 select 值並合並結果。
select id, 'table1' as table_name, 'A' as column_name, a as value from table1 where a > 10
union all
select id, 'table1' as table_name, 'B' as column_name, b as value from table1 where b > 10
union all
select id, 'table2' as table_name, 'C' as column_name, c as value from table2 where c > 10
union all
select id, 'table2' as table_name, 'D' as column_name, d as value from table2 where d > 10
union all
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.