我正在转换为SQL Server的Oracle查询
select
(select LISTAGG(mycase, ', ') WITHIN GROUP (ORDER BY my_gross_amount)
from
(select *
from ( select th.CONTACT_ID,
th.created_dt,
sum(th.my_gross_amount) my_gross_amount,
mycase
from mySch.trans_his th
join mySch.fund f on f.fund = th.fund
group by contact_id, th.created_dt, mycase)
where rownum < 4 ) a
group by contact_id, created_dt
) as DetailNotes
from mySch.trans_his t
我已转换的MS SQL查询
select
(select STUFF((
SELECT ', '+ mycase
from (select TOP(3) th.CONTACT_ID,
th.created_dt,
sum(th.my_gross_amount) my_gross_amount,
mycase
from mySch.dbo.trans_his th
join mySch.dbo.fund f on f.fund = th.fund
group by contact_id, th.created_dt, mycase)subQueryA
Where subQueryA.my_gross_amount = subQueryB.my_gross_amount FOR XML PATH('')),1 ,1, '')
from (select TOP (3) th.CONTACT_ID,
th.created_dt,
sum(th.my_gross_amount) my_gross_amount,
mycase
from mySch.dbo.trans_his th
join mySch.dbo.fund f on f.fund = th.fund
group by contact_id, th.created_dt, mycase) subQueryB
group by contact_id, created_dt, my_gross_amount
) as DetailNotes
from mySch.dbo.trans_his t
同样的查询在Oracle中需要几秒钟,但在sql server中永远需要。不确定这是否是将listAgg从oracle转换为SQl服务器的最佳方法。 并且不确定SQL查询是否卡在循环中。
Oracle Version 12c
MS SQL 2016版
有没有更好的方法在SQL Server中重写此查询?
使用以下链接转换ListAgg函数
更新:
trans_his table details
trans_id varchar2(20)
firm_id varchar2(20)
fund varchar2(20)
contact_id varchar2(20)
trade_cl varchar2(2)
my_gross_amount number(15,2)
created_dt date
资金表详情
fund varchar2(20)
mycase varchar2(100)
start_date date
end_date date
created_by varchar2(20)
created_dt date