gpt4 book ai didi

sql - 摆脱昂贵的自连接

转载 作者:行者123 更新时间:2023-12-01 13:41:45 25 4
gpt4 key购买 nike

我有一个这样的 SQL 语句

SELECT  
pa.col1,
SUM(ps.col2) col2,
SUM(psl.col2) col2_previous_month
FROM
pa
LEFT JOIN
ps ON pa.Id = ps.Id AND ps.date = @currDate
LEFT JOIN
ps as psl ON psl.Id = ps.Id AND psl.date = dateadd(month, - 1, @currDate)
GROUP BY
pa.col1;

这个 SQL 经常被调用,因为表 ps有 100M 行左连接正在伤害。有没有办法使用 left Join 重写它?

问候
缺口

最佳答案

也许这会有所帮助

    Select pa.col1
,col2 =isnull(sum(case when ps.date=@currDate then ps.col2 else null end),0)
,col2_prior=isnull(sum(case when ps.date=dateadd(month,-1,@currDate) then ps.col2 else null end),0)
From pa
JOIN ps as ps ON pa.Id = ps.Id
and ps.date in (@currDate,dateadd(month,-1,@currDate))
Group By pa.col1

关于sql - 摆脱昂贵的自连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39549535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com