2016-04-06 8 views
0

Ich habe 2 TabellenUnion Alle in SQL Join und

t1: CustID CustName 

     1  aaa 
     2  bbb 

t2: CustID Tax1 Tax2 

     1  5  10 
     2  4  8 

Ich brauche eine Abfrage zu schreiben, die als Ergebnis bringt folgende Tabelle

t3: CustID CustName TaxName TaxValue 

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

Ich konnte Union Alle

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

union all 

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

aber konnte hier nicht beitreten CustName von t1

Antwort

1

Verwenden Sie einfach eine Unterabfrage:

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;