簡體   English   中英

聯合所有並加入SQL

[英]Union All and Join in 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

只需使用子查詢:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM