【问题标题】:How to Sum and Group Union of Two Tables with Different Column Names in SQL Server如何在 SQL Server 中对具有不同列名的两个表进行求和和分组
【发布时间】:2014-06-05 23:03:33
【问题描述】:

以下查询成功返回供应商在某个日期范围内的信用卡和支票付款。我一直无法使用别名编写外部选择语句来汇总供应商的金额和分组。我该如何做这个查询?

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'}

【问题讨论】:

    标签: sql sql-server


    【解决方案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
    

    【讨论】:

    • 我尝试了建议的解决方案,但出现 ODBC 错误“意外的额外令牌:供应商”是什么原因造成的?
    • 查看我的编辑 - NOSYNC 表提示导致查询无法在本地 SSMS 中执行,我想它们也会导致 ODBC 解析出现问题。
    • 我错过了删除 NOSYNC。这次我完全按照建议运行了查询。这次我收到了“意外的额外令牌:AS”错误。我删除了外部选择并只运行了联合,它工作得很好。我不知道这是否重要,但我正在查询链接服务器。
    • 您可以尝试删除派生表别名,但这对我来说似乎违反直觉。在这一点上,我认为您可能希望将此作为一个问题,或者将其作为 ODBC 问题,或者作为 StackExchange 的数据库管理员站点。您在使用 ODBC 时遇到的问题目前超出我的了解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 2018-05-08
    相关资源
    最近更新 更多