在此查询中消除DISTINCT的方法

时间:2015-06-29 21:24:33

标签: sql aggregate-functions

此查询返回正确的SUM,但它自身重复:

SELECT [GrandTotal] = (total1 + total2)
FROM (SELECT(SELECT SUM([Total]) [total1] FROM [ooc].[RentalRevenue2] WHERE [CheckOut] >= '2015-01-01' AND [CheckOut] < '2015-06-30' AND [CampaignName] NOT LIKE '%Non-Cancellable%') as total1,
            (SELECT SUM([Total]) [total2] FROM [ooc].[Revenue2] WHERE [DateConfirmationReceived] >= '2015-01-01' AND [DateConfirmationReceived] < '2015-06-30' AND [CampaignName] LIKE '%Non-Cancellable%') as total2
      FROM [ooc].[Revenue2]) T 

我可以通过添加DISTINCT消除此行为。

SELECT DISTINCT [GrandTotal] = (total1 + total2)
FROM (SELECT(SELECT SUM([Total]) [total1] FROM [ooc].[RentalRevenue2] WHERE [CheckOut] >= '2015-01-01' AND [CheckOut] < '2015-06-30' AND [CampaignName] NOT LIKE '%Non-Cancellable%') as total1,
            (SELECT SUM([Total]) [total2] FROM [ooc].[Revenue2] WHERE [DateConfirmationReceived] >= '2015-01-01' AND [DateConfirmationReceived] < '2015-06-30' AND [CampaignName] LIKE '%Non-Cancellable%') as total2
      FROM [ooc].[Revenue2]) T 

我不认为这是执行此SUM查询的正确方法。

2 个答案:

答案 0 :(得分:1)

执行SUM操作的两个子查询似乎与包含它们的SELECT ... FROM [ooc].[Revenue2]查询没有任何关系。但是,因为它们位于该构造中,所以[ooc].[Revenue2]中的每一行的输出中都会有一行。根据我在此处看到的内容,您可以安全地将查询简化为以下内容:

SELECT [GrandTotal] = 
       (SELECT SUM([Total]) [total1] 
          FROM [ooc].[RentalRevenue2] 
         WHERE [CheckOut] >= '2015-01-01' 
           AND [CheckOut] < '2015-06-30'
           AND [CampaignName] NOT LIKE '%Non-Cancellable%') +
       (SELECT SUM([Total]) [total2]
          FROM [ooc].[Revenue2]
         WHERE [DateConfirmationReceived] >= '2015-01-01' 
           AND [DateConfirmationReceived] < '2015-06-30'
           AND [CampaignName] LIKE '%Non-Cancellable%')

正如@Quassnoi所指出的,如果这些子查询中的任何一个都没有导致行,则最终结果将是NULL。在每个子查询周围缠绕ISNULL(..., 0)可以避免这种情况。我会把它留给OP,因为他们可能知道这样的结果是否可能。

答案 1 :(得分:1)

SELECT  SUM(Total)
FROM    (
        SELECT  total
        FROM    Revenue2
        WHERE   DateConfirmationReceived >= '2015-01-01'
                AND DateConfirmationReceived < '2015-06-30'
                AND CampaignName LIKE '%Non-Cancellable%'
        UNION ALL
        SELECT  total
        FROM    RentalRevenue2
        WHERE   checkout >= '2015-01-01'
                AND checkout < '2015-06-30'
                AND CampaignName NOT LIKE '%Non-Cancellable%'
        ) q