简体   繁体   中英

Union All and Join in SQL

I have 2 tables

t1: CustID    CustName

       1        aaa
       2        bbb

t2: CustID    Tax1    Tax2

       1      5     10
       2      4     8

I need to write a query which brings as a result the following table

t3: CustID    CustName    TaxName    TaxValue

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

I was able to Union All

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

union all

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

but couldn't join here CustName from t1

Just use a subquery:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM