1

我这里有两张桌子:

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
4

2 回答 2

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 |

看到这个 SQLFiddle


早些时候

您可以像这样使用 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 |

看到这个 SQLFiddle

于 2013-09-05T06:30:05.050 回答
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

=> sql 小提琴演示

您可以轻松添加 position = 3, 4 然后只需将行添加到 cte

于 2013-09-05T06:28:05.707 回答