我需要通过读取配置并将其应用于纯SQL中的数据集来生成目标表结构。 我有以下格式的两个数据表
T1
|Col1|Col2|
|1 |12 |
|2 |13 |
|3 |14 |
|4 |15 |
|5 |16 |
T2
|Col1|Col2|
|11 |22 |
|21 |23 |
|31 |24 |
|41 |25 |
|51 |26 |
以及下面给出的配置表
TC
|Tbl|Col |Val|Text|
|T1 |Col1|1 |A |
|T1 |Col1|3 |B |
|T1 |Col2|15 |A |
|T2 |Col2|26 |A |
|T2 |Col1|11 |B |
我需要提出以下目标表
TGT1
|Col1|Col2|Text|
|1 |12 |A |
|2 |13 |NULL|
|3 |14 |B |
|4 |15 |A |
|5 |16 |NULL|
TGT2
|Col1|Col2|Text|
|11 |22 |B |
|21 |23 |NULL|
|31 |24 |NULL|
|41 |25 |NULL|
|51 |26 |A |
逻辑是读取完整的T1和T2并生成TC表中提供的文本字段(Tbl和Col指的是设置中的实际表和列)
我对如何产生这个输出完全感到困惑。任何人都可以提供一些指示开始吗?如果这有助于任何人摆弄!
WITH
T1(Col1,Col2) AS
(SELECT 1,12 UNION ALL
SELECT 2,13 UNION ALL
SELECT 3,14 UNION ALL
SELECT 4,15 UNION ALL
SELECT 5,16 ),
T2(Col1,Col2) AS
(SELECT 11,22 UNION ALL
SELECT 21,23 UNION ALL
SELECT 31,24 UNION ALL
SELECT 41,25 UNION ALL
SELECT 51,26 ),
TC (Tbl,Col,Val,Text) AS
(SELECT 'T1','Col1',1,'A' UNION ALL
SELECT 'T1','Col1', 3,'B' UNION ALL
SELECT 'T1','Col2',15,'A' UNION ALL
SELECT 'T2','Col2',26,'A' UNION ALL
SELECT 'T2','Col1',11,'B' )
SELECT ????
答案 0 :(得分:1)
这听起来像<permission class="org.osgi.framework.AdminPermission" name="*" actions="*"/>
。这是一种方法,以left join
为例:
t1
你会以同样的方式接近select t1.*, tc.text
from t1 left join
tc
on (t1.col1 = tc.val and tc.tbl = 't1' and tc.col = 'Col1') or
(t1.col2 = tc.val and tc.tbl = 't1' and tc.col = 'Col2') or
(t1.col3 = tc.val and tc.tbl = 't1' and tc.col = 'Col3') ;
。
答案 1 :(得分:1)
以下是我的尝试:
SELECT T1.Col1, T1.Col2, TC.Text
FROM
T1 LEFT JOIN TC
ON TC.Tbl = 'T1'
AND (
T1.Col1 = TC.Val AND TC.Col = 'Col1'
OR T1.Col2 = TC.Val AND TC.Col = 'Col2'
)
SELECT T2.Col1, T2.Col2, TC.Text
FROM
T2 LEFT JOIN TC
ON TC.Tbl = 'T2'
AND (
T2.Col1 = TC.Val AND TC.Col = 'Col1'
OR T2.Col2 = TC.Val AND TC.Col = 'Col2'
)
答案 2 :(得分:1)
SELECT
T1.Col1,
T1.Col2,
TC.[Text]
FROM T1
LEFT JOIN TC ON TC.Tbl = 'T1'
AND TC.VAL = CASE TC.Col
WHEN 'Col1' THEN T1.Col1
WHEN 'Col2' THEN T1.Col2
END;
SELECT
T2.Col1,
T2.Col2,
TC.[Text]
FROM T2
LEFT JOIN TC ON TC.Tbl = 'T2'
AND TC.VAL = CASE TC.Col
WHEN 'Col1' THEN T2.Col1
WHEN 'Col2' THEN T2.Col2
END;
这是一个有效的SQLFiddle: http://sqlfiddle.com/#!6/8b7c0/9/0
答案 3 :(得分:1)
我会做更像这样的事情:
with u as
(select
tc.tbl, tc.col, tc.val, [Text]
from
tc inner join
(select 't1' as tbl, 'col1' as col, col1 as val from t1 union
select 't1' as tbl, 'col2' as col, col2 as val from t1 union
select 't2' as tbl, 'col1' as col, col1 as val from t2 union
select 't2' as tbl, 'col2' as col, col2 as val from t2) s on
tc.tbl = s.tbl and
tc.col = s.col and
tc.val = s.val)
select 't1' as tbl, col1, col2, [text] from
t1 left outer join
u on
tbl = 't1' and
case when col='col1' then col1 else col2 end = val
union
select 't2', col1, col2, [text] from
t2 left outer join
u on
tbl = 't2' and
case when col='col1' then col1 else col2 end = val