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]
                    --(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これがトリックです。すでに結合を定義しているので、ステートメントを使用して Not Sold と異なる StageName を合計するだけです。

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