我已经看过一些关于使用这三个函数的线程,但根据我读到的内容,我无法得到我想要的结果。
我正在使用SQL SERVER 2012.该表是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
由于
答案 0 :(得分:2)
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
子句。
答案 1 :(得分:0)
替换
HAVING marketvalue > 1
与
HAVING Pcount > 1