Reputation: 9490
Sorry if the title is confusing, I'll try to explain. I have a query that needs to have a couple of aggregate fields, but I don't know how to write one of them. Here's the current script:
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];
You'll notice a commented out line. On that line I want to get a count of all Opportunities
that are not marked as 'Not Sold'
. It works if I add [O].[Id]
to the GROUP BY
, but then the result set expands because the grouping gets messed up.
How can I get the count I want?
Thanks in advance!
Upvotes: 1
Views: 300
Reputation: 2317
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];
This is the trick, you already defined a join so you just need to Sum the StageName differents from Not Sold using a CASE
statement
SUM(CASE WHEN [O].[StageName] != 'Not Sold' THEN 1 ELSE 0 END)
Upvotes: 1