如何在SQL Server中对具有不同列名的两个表进行求和和联合

时间:2014-06-05 23:03:34

标签: sql sql-server

以下查询成功返回信用卡并按供应商检查日期范围的付款。我无法使用别名来编写外部select语句,以按供应商对Amount和group求和。我该怎么做这个查询?

SELECT
BillPaymentCreditCard.PayeeEntityRefFullName as Vendor, BillPaymentCreditCard.Amount as Amount 
FROM
BillPaymentCreditCard NOSYNC 
WHERE
BillPaymentCreditCard.TxnDate >= {d'2014-01-01'} and BillPaymentCreditCard.TxnDate <= {d'2014-02-01'} 

UNION ALL

SELECT
BillPaymentCheck.PayeeEntityRefFullName as Vendor, BillPaymentCheck.Amount as Amount 
FROM
BillPaymentCheck NOSYNC 
WHERE 
BillPaymentCheck.TxnDate >= {d'2014-01-01'} and  BillPaymentCheck.TxnDate <= {d'2014-02-01'}

1 个答案:

答案 0 :(得分:1)

这应该这样做。 - 每条评论 - 删除nosync表提示。

SELECT Vendor, SUM(Amount) AS TotalAmount
FROM (

    SELECT BillPaymentCreditCard.PayeeEntityRefFullName as Vendor, BillPaymentCreditCard.Amount as Amount
    FROM BillPaymentCreditCard
    WHERE BillPaymentCreditCard.TxnDate >= {d'2014-01-01'}
         and BillPaymentCreditCard.TxnDate <= {d'2014-02-01'}

    UNION ALL

    SELECT BillPaymentCheck.PayeeEntityRefFullName as Vendor, BillPaymentCheck.Amount as Amount
    FROM BillPaymentCheck
    WHERE BillPaymentCheck.TxnDate >= {d'2014-01-01'}
         and BillPaymentCheck.TxnDate <= {d'2014-02-01'}
    ) AS Vendors
GROUP BY Vendor