如何从需要过滤器的子查询聚合数据?

时间:2012-06-14 21:13:04

标签: sql sql-server tsql sql-server-2005

很抱歉,如果标题令人困惑,我会尝试解释。我有一个查询需要有几个聚合字段,但我不知道如何编写其中一个。这是当前的脚本:

DECLARE @Date DATETIME;
DECLARE @FromDate VARCHAR(25);
DECLARE @ToDate VARCHAR(25);

SET     @Date = GETDATE();
SET     @FromDate = CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(@Date) - 1), @Date),101);
SET     @ToDate = CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(DATEADD(mm, 1, @Date))), DATEADD(mm,1,@Date)), 101);

SELECT  DISTINCT    [A].[Name],
                    COUNT([O].[Id]) AS [OpportunityCount],
                    (CASE WHEN (SUM([O].[Amount]) IS NULL) THEN 0.00 ELSE SUM([O].[Amount]) END) AS [OpportunityTotalAmounts]
                    --(SELECT COUNT(1) FROM [Opportunity] AS [O1] WHERE ([O1].[Id] = [O].[Id]) AND ([O1].[StageName] != 'Not Sold'))
FROM                [Account] AS [A]
                    JOIN [RecordType] AS [RT] ON ([A].[RecordTypeId] = [RT].[Id])
                    JOIN [Contact] AS [C] ON ([A].[Id] = [C].[AccountId])
                    JOIN [OpportunityContactRole] AS [OCR] ON ([C].[Id] = [OCR].[ContactId])
                    LEFT OUTER JOIN [Opportunity] AS [O] ON ([OCR].[OpportunityId] = [O].[Id])
WHERE               ([RT].[Name] = 'PHX')
                    AND ([A].[TypeMS__c] != 'Customer')
                    AND ([O].[CreatedDate] BETWEEN @FromDate AND @ToDate)
GROUP BY            [A].[Name];

你会注意到一条注释掉的线。在该行中,我想要计算未标记为Opportunities的所有'Not Sold'。如果我将[O].[Id]添加到GROUP BY,它会有效,但结果集会扩展,因为分组会搞砸。

如何获得我想要的计数?

提前致谢!

1 个答案:

答案 0 :(得分:1)

DECLARE @Date DATETIME;
DECLARE @FromDate VARCHAR(25);
DECLARE @ToDate VARCHAR(25);

SET     @Date = GETDATE();
SET     @FromDate = CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(@Date) - 1), @Date),101);
SET     @ToDate = CONVERT(VARCHAR(25), DATEADD(dd, -(DAY(DATEADD(mm, 1, @Date))), DATEADD(mm,1,@Date)), 101);

SELECT  DISTINCT    [A].[Name],
                    COUNT([O].[Id]) AS [OpportunityCount],
                    (CASE WHEN (SUM([O].[Amount]) IS NULL) THEN 0.00 ELSE SUM([O].[Amount]) END) AS [OpportunityTotalAmounts],
                    SUM(CASE WHEN [O].[StageName] != 'Not Sold' THEN 1 ELSE 0 END) 
FROM                [Account] AS [A]
                    JOIN [RecordType] AS [RT] ON ([A].[RecordTypeId] = [RT].[Id])
                    JOIN [Contact] AS [C] ON ([A].[Id] = [C].[AccountId])
                    JOIN [OpportunityContactRole] AS [OCR] ON ([C].[Id] = [OCR].[ContactId])
                    LEFT OUTER JOIN [Opportunity] AS [O] ON ([OCR].[OpportunityId] = [O].[Id])
WHERE               ([RT].[Name] = 'PHX')
                    AND ([A].[TypeMS__c] != 'Customer')
                    AND ([O].[CreatedDate] BETWEEN @FromDate AND @ToDate)
GROUP BY            [A].[Name];

这是诀窍,你已经定义了一个连接,所以你只需要使用CASE语句来总结来自Not Sold的StageName不同

 SUM(CASE WHEN [O].[StageName] != 'Not Sold' THEN 1 ELSE 0 END)