T-SQL通过CTE或带有来自视图的列的子查询过滤聚合列

时间:2018-10-31 17:47:00

标签: sql-server subquery case aggregate common-table-expression

在SQL Server中,正在尝试从计算中过滤结果,其中 sum(OutShares) > 5。不能在Where子句中使用聚合,并且只会过滤symbol > 5,因此不会聚合聚合。我相信我需要使用CTE或子查询。

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
where 
    OutShares > 5.0
group by 
    symbol, last_name; 

结果:

Symbol  OutShares       last_name
---------------------------------
ATI     2.087600649     Jill
ATI     2.546492791     Bernie
ATI     1.13889437      Evie
ATI     1.603800006     Luke
BO      5.00000000      Jack

所需结果:

Symbol  OutShares       last_name
------------------------------------------------
ATI     7.38            Jill Bernie Evie Luke
BO      5.00            Jack

2 个答案:

答案 0 :(得分:0)

您可以通过以下方式使用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

但是从您期望的结果看来,如果它是sql server 2017,您似乎需要STRING_AGG()

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 server版本

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

答案 1 :(得分:0)

我想你想要

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) OutShares,
       STUFF(
              (
                SELECT ' '+ Last_Name
                FROM CTE TT
                WHERE TT.Symbol = T.Symbol
                FOR XML PATH('')
              ), 1, 1, ''
       ) last_name
FROM CTE
GROUP BY Symbol;