全联盟并加入SQL

时间:2016-04-06 22:04:55

标签: sql

我有2张桌子

t1: CustID    CustName

       1        aaa
       2        bbb

t2: CustID    Tax1    Tax2

       1      5     10
       2      4     8

我需要编写一个查询,其结果是下表

t3: CustID    CustName    TaxName    TaxValue

      1       aaa       Tax1       5
      1       aaa       Tax2       10
      2       bbb       Tax1       4
      2       bbb       Tax2       8

我能够全联盟

Select CustID,'Tax1' [TaxName], Tax1 [TaxValue]
from t2

union all

Select CustID,'Tax2' [TaxName], Tax2 [TaxValue]
from t2

但无法从t1

加入CustName

1 个答案:

答案 0 :(得分:1)

只需使用子查询:

select t2.custid, t1.custname, t2.taxname, t2.taxvalue
from ((Select CustID, 'Tax1' as [TaxName], Tax1 as [TaxValue] from t2
      ) union all
      (Select CustID, 'Tax2' as [TaxName], Tax2 as [TaxValue] from t2
      )
     ) t2 join
     t1
     on t1.custid = t2.custid;