SQL 分组依据 return 多个值

SQL Group By return multiple Values

我有一个问题,我需要从 table

中获取一些数据的总数

我需要执行 3 种类型的分组 1. 1个分组应该在合作伙伴上 2. 1 国家分组 3. 1 组日期

我有一个table像这样

PartnerId, CountryId, Date
  1           2       10-01-2017
  1           2       10-01-2017
  1           3       10-01-2017
  1           1       10-01- 2013

我希望 return 数据集是

1     2    10-01-2017 - total 2
1     3    10-01-2017 - total 1
1     1    10-01-2013 - total 1

这是我为合作伙伴分组所做的尝试,但我得到了不正确的值并且重复了错误的总计数

  ELSE IF(@partnerId > 0 AND @CountryId = 0 AND @InvoiceMonth IS NULL)
        BEGIN
             SET @sql = @sql + ' INSERT INTO #FinalBucket2
          SELECT  b.PartnerId, Null, b.CountryId, NULL, a.Local_Closed_Calendar_Month, b.Total
         FROM #DataBucket2 a WITH(NOLOCK),
          ( SELECT  PartnerId, CountryId, count(*) Total
         FROM #DataBucket2 WITH(NOLOCK)
         GROUP BY PartnerId, CountryId ) b
         WHERE a.PartnerId = b.PartnerId 
       '
        END

在这里,如果我传递 PartnerId,则分组应该按合作伙伴进行。 如果我传递了 countryId 而没有 PartnerId 和 InvoiceMonth,那么分组应该在国家/地区。 如果我只传递 InvoiceMonth 那么分组应该只在 invoiceMonth

您可以使用下面的SQL。这将按 partnerid、countryid 和 local_closed_calendar_month 分组。如果你想按国家分组然后所有合作伙伴,那么你只需要切换它们。

SELECT partnerId,
       countryId,
       local_closed_calendar_month,
       COUNT(*) Total
  FROM #DataBucket2
 GROUP BY partnerId, 
          countryId,
          local_closed_calendar_month