如何在sql中添加两个查询结果作为单个结果?

时间:2013-12-10 06:10:51

标签: sql sql-server database

我需要添加两个查询输出作为单个结果。

第一个查询输出来自“InvoiceDetail”表:

InvoiceID, POSCode, CQuantity, CPrice, TCost, AmountPaid

19327   07310000504 1   22.38   22.38   368.59
19326   07161030192 1   28.90   28.90   5402.69
19326   07013711044 2   12.53   25.06   5402.69
19327   07310000622 2   6.28    12.56   368.59
19326   07013721043 1   25.07   25.07   5402.69
19327   07310000626 2   6.28    12.56   368.59
19327   01230050268 2   37.15   74.30   368.59
19326   04210000910 2   9.84    19.68   5402.69
19327   01230050271 1   37.15   37.15   368.59 

我的第二个查询输出来自“InvoiceCharge”表:

 InvoiceID  totalCharge
  19326 9.00
  19326 6.00

最后我想输出如下:

InvoiceID,POSCode,CQuantity,CPrice,TCost,AmountPaid,totalCharge

19327   07310000504 1   22.38   22.38   368.59   0.00
19326   07161030192 1   28.90   28.90   5402.69  15.00
19326   07013711044 2   12.53   25.06   5402.69  15.00
19327   07310000622 2   6.28    12.56   368.59    0.00
19326   07013721043 1   25.07   25.07   5402.69  15.00
19327   07310000626 2   6.28    12.56   368.59   0.00
19327   01230050268 2   37.15   74.30   368.59   0.00
19326   04210000910 2   9.84    19.68   5402.69  15.00
19327   01230050271 1   37.15   37.15   368.59    0.00

这就是我需要的......

此处InvoiceID 19326收费(9.00 + 6.00)= 15.00 和InvoiceID 19327免费,因此在InvoiceCharge表中找不到任何行。

2 个答案:

答案 0 :(得分:1)

请尝试以下查询

select 
        InvoiceID, 
        POSCode, 
        CQuantity, 
        CPrice, 
        TCost, 
        AmountPaid, 
        (SELECT sum(totalCharge) FROM InvoiceCharge IC WHERE IC.InvoiceID = ID.InvoiceID) AS totalCharge 
from InvoiceDetail ID

答案 1 :(得分:0)

试试这个:

select  InvoiceID, 
    POSCode, 
    CQuantity, 
    CPrice, 
    TCost, 
    AmountPaid,
    (case when a.charge is null then 0 else a.charge end)) as totalCharge
    from InvoiceDetail left join (SELECT sum(totalCharge) as charge , InvoiceCharge.InvoiceID FROM InvoiceCharge group by InvoiceCharge.InvoiceID) a on InvoiceCharge.InvoiceID = InvoiceDetail.InvoiceID