我这里有两张桌子:
Table1
Version | Position | PIN
1 | 1 | 1111
1 | 2 | 2222
2 | 1 | 3333
2 | 2 | 4444
我有另一张桌子
Table2
Name | Version | Position1 | Position2
'Phone1' | 1 | A | B
'Phone2' | 2 | C | D
实际上Table2.Position1 =(Table1.Position = 1)和Table2.Position2 =(Table1.Position = 2)。还有Table1.Version = Table2.Version。
我想制作看起来像这样的视图
Table3
Name | P_Name | PIN
'Phone1' | A | 1111
'Phone1' | B | 2222
'Phone2' | C | 3333
'Phone2' | D | 4444
答案 0 :(得分:2)
WITH CTE(Name, Version, Pos, Position)
AS (
SELECT Name, Version, Position1, 1 FROM Table2
UNION ALL
SELECT Name, Version, Position2, 2 FROM Table2
)
SELECT T2.Name, T2.Pos, T1.PIN
FROM Table1 t1
JOIN CTE t2
ON t1.Version = t2.Version
AND t1.Position = t2.Position;
输出:
| NAME | POS | PIN |
|--------|-----|------|
| Phone1 | A | 1111 |
| Phone1 | B | 2222 |
| Phone2 | C | 3333 |
| Phone2 | D | 4444 |
<击> 您可以使用JOIN执行此操作:
SELECT t2."Name", t1."Position", t1."PIN"
FROM Table1 AS t1
JOIN Table2 AS t2
ON t1."Version" = t2."Version"
AND ( (t1."Position" = 1 AND t2."Position1" = t1."PIN")
OR (t1."Position" = 2 AND t2."Position2" = t1."PIN")
)
输出:
| NAME | POSITION | PIN |
|--------|----------|------|
| Phone1 | 1 | 1111 |
| Phone1 | 2 | 2222 |
| Phone2 | 1 | 3333 |
| Phone2 | 2 | 4444 |
<击>
答案 1 :(得分:0)
我认为最优雅和可扩展的方式是:
with cte(Name, Version, P_Name, Position) as (
select Name, Version, Position1, 1 from Table2
union all
select Name, Version, Position2, 2 from Table2
)
select
T2.Name, T2.P_Name, T1.PIN
from Table1 as T1
left outer join cte as T2 on
T2.Position = T1.Position and T2.Version = T1.Version
order by Name, P_Name
您可以轻松添加position = 3,4,然后只需将行添加到cte
中