вы можете использовать cte ниже
with cte as
(
select symbol, sum(qty) * cast(Shares as decimal) As OutShares, last_name
from holding h
join security s on h.id=s.id
join account a on h.p = a.p
join manager m on a.aid=m.id
group by symbol, last_name
) select * from cte where OutShares>5
Но из твоего желаемого результата мне кажется, тебе нужно STRING_AGG()
, если это sql server 2017
with cte as
(
select symbol, sum(qty) * cast(Shares as decimal) As OutShares, last_name
from holding h
join security s on h.id=s.id
join account a on h.p = a.p
join manager m on a.aid=m.id
group by symbol, last_name
) select symbol,sum(OutShares),
STRING_AGG(last_name, ', ') as last_name from cte
group by symbol
ниже версии сервера sql
with cte as
(
select symbol, sum(qty) * cast(Shares as decimal) As OutShares, last_name
from holding h
join security s on h.id=s.id
join account a on h.p = a.p
join manager m on a.aid=m.id
group by symbol, last_name
)
select symbol, sum(OutShares),
STUFF((SELECT distinct ',' + t2.last_name
from cte t2
where t1.symbol= t2.symbol
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,0,'') name
from cte t1 group by symbol