[英]GROUP BY, HAVING, and COUNT to get aggregated results
我已經看到了一些有關使用這三個函數的主題,但是根據所閱讀的內容,我無法獲得想要的結果。
我正在使用SQL SERVER2012。表為APXFirm.AdvApp.vPerformance,這是表架構
我嘗試了以下查詢:
USE APXFirm
SELECT PortfolioBaseCode
,COUNT( portfoliobasecode) AS Pcount
FROM APXFirm.AdvApp.vPerformance
WHERE rowtypecode = 'd'
and DetailKeyCode is NOT NULL
and NetOrGrossCode = 'n'
and DetailKeyCode <> 'us'
and PortfolioBaseCode IN ('test','test2')
GROUP BY PortfolioBaseCode,
NetOrGrossCode,
RowTypeCode ,
DetailKeyCode ,
MarketValue
HAVING marketvalue > 1
但這給了我這樣的結果:
PortfolioBaseCode Pcount
test 1
test 1
test 1
test2 1
test2 1
test2 1
test2 1
我想要這樣的結果
PortfolioBaseCode Pcount
test 3
test2 4
我不確定是否需要子查詢,聯接或在計數中使用distinct實現此目的或其他目的。 我也嘗試過這一行,但沒有改變結果。
,COUNT( DISTINCT portfoliobasecode) AS Pcount
謝謝
您的group by
列過多。 我想您只想要:
SELECT PortfolioBaseCode, COUNT( portfoliobasecode) AS Pcount
FROM APXFirm.AdvApp.vPerformance
WHERE rowtypecode = 'd' AND
DetailKeyCode is NOT NULL AND
NetOrGrossCode = 'n' AND
DetailKeyCode <> 'us' AND
PortfolioBaseCode IN ('test', 'test2')
GROUP BY PortfolioBaseCode
HAVING SUM(marketvalue) > 1;
我實際上不確定HAVING
子句應該做什么。 也許您可以將其刪除。 也許您可以將邏輯marketvalue > 1
移到WHERE
子句。
更換
HAVING marketvalue > 1
與
HAVING Pcount > 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.