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]
                    --(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,但是结果集会扩展,因为分组被搞砸了。

我怎样才能得到我想要的计数?

提前致谢!

4

1 回答 1

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语句将 StageName 与 Not Sold 的不同之处求和

 SUM(CASE WHEN [O].[StageName] != 'Not Sold' THEN 1 ELSE 0 END) 
于 2012-06-14T21:18:30.537 回答