【发布时间】:2018-01-30 02:00:39
【问题描述】:
我有一个问题,我需要从表中获取某些数据的总数
我需要执行 3 种类型的分组 1. 1个分组应该在伙伴上 2. 1个国家分组 3. 1个日期分组
我有一张这样的桌子
PartnerId, CountryId, Date
1 2 10-01-2017
1 2 10-01-2017
1 3 10-01-2017
1 1 10-01- 2013
我希望返回数据集是
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 上
【问题讨论】:
-
为了获得 a.Local_Closed_Calendar_Month 你做了一些自加入?
-
是的,#DataBucket2 包含我需要的所有列的主数据,因此我做到了。有办法解决吗?
-
为什么不直接在这个选择中添加该列,SELECT PartnerId, CountryId, count(*) Total FROM #DataBucket2 WITH(NOLOCK) GROUP BY PartnerId, CountryId?
-
@FerdinandGaspar:我猜你是对的,现在如果我想按国家/地区分组,我该怎么做?所以如果我想要像 X 国这样的东西,所有的参与者所有的日期 = 总数
-
您能否在上面的示例数据中提供 a.Local_Closed_Calendar_Month,好吗? TY
标签: sql sql-server stored-procedures group-by dynamic-sql