我有一個問題,我需要從表中得到一些數據的總數SQL集團通過返回多個值
有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那麼分組應該在發票月份上
爲了得到a.Local_Closed_Calendar_Month,你做了一些自聯接嗎? –
是的,#DataBucket2包含我需要的所有列的主數據,因此我做到了。有沒有辦法解決它? –
爲什麼不在這個select,SELECT PartnerId,CountryId,count(*)總數FROM#DataBucket2 WITH(NOLOCK)GROUP BY PartnerId,CountryId中添加該列? –