合并两个表并在基于结果的第二个表中创建新列

时间:2017-02-20 11:01:06

标签: sql sql-server tsql

我有两个临时表,从中想要将它们两者结合起来就像以下一样。有什么办法可以做到这一点吗?在最终结果中,应该包含基于第二表Tax Type的新列。税种的数量未知。它可能会不时变化。

Table : Work
    +-----------+----------------+
    |  WorkId   |     Work       |
    +-----------+----------------+
    |  1080     |  "Work One"    |
    |  1081     |  "Work Two"    |
    |  1082     |  "Work Tree"   |
    +-----------+----------------+

Table : TaxDetails
    +--------+----------+---------+---------+
    | Taxid  |  TaxType |    Amt  |  WorkId |
    +--------+----------+---------+---------+
    |   1    |   VAT    |   120.0 |   1080  |
    |   1    |   VAT    |   300.0 |   1081  |
    |   2    |   S.Tax  |   150.0 |   1083  |
    |   2    |   S.Tax  |   101.0 |   1080  |
    +--------+----------+---------+---------+

Final Result :
    +--------+-------------+-------+--------+
    | WorkId |   Work      |   Vat |  S.Tax |
    +--------+-------------+-------+--------+
    |  1080  | "Work One"  |  120.0|   101.0|
    |  1081  | "Work Two   |  300.0|   0.0  |
    |  1082  | "Work Three"|  0.0  |   0.0  |
    +--------+-------------+-------+--------+

2 个答案:

答案 0 :(得分:0)

可以使用简单的案例陈述,列别名和子选择来获得税收总额。如果ISNULL没有可用的税值,则WorkID将返回0:

SELECT
W.WorkId
,Work
,ISNULL(VAT,0) AS 'VAT'
,ISNULL(Service_Tax,0) AS 'Service Tax'
FROM Work AS W
LEFT JOIN  (
    SELECT
    WorkID
    ,SUM(CASE TaxType WHEN 'VAT' THEN amt ELSE 0 END) AS VAT
    ,SUM(CASE TaxType WHEN 'S.Tax' THEN amt ELSE 0 END) AS Service_Tax
    FROM TaxDetails
    GROUP BY workID
    ) AS T
    ON w.workID = T.WorkID

答案 1 :(得分:0)

select w.WorkId, w.work
     , isnull(v.Amt,0) as Vat
     , isnull(s.Amt,0) as Stax
from work w 
left join TaxDetails v 
 on v.WorkId = w.WorkId 
and v.Taxid = 1
left join TaxDetails s 
 on s.WorkId = w.WorkId 
and s.Taxid = 2