我有两个查询不同表并返回相似字段的 SQL 查询:
User - Role - Category - Points
和
User - Role - Category - Target
我的查询如下所示:
select
acs.UserID,
acs.RoleID,
acs.CategoryID,
sum(acs.Points)
from acs
和
select
tb.UserID,
tb.RoleID,
tb.CategoryID,
sum(
(
(DATEDIFF(dd, (case when @start >= tb.StartDate then @start else tb.StartDate end), (case when @end <= tb.EndDate then @end else tb.EndDate end)) + 1)
) * tb.dailyMed
) as Target
from tb
我想结束的是这样的:
User - Role - Category - Points - Target
每个单独的查询运行时间不到 1 秒,但是当我尝试使用内部连接将它们组合起来时,运行时间超过 3 分钟。
我希望有一种更有效的方法来做到这一点,但我似乎找不到。
*编辑我的内部连接看起来像这样
select
acs.UserID,
acs.RoleID,
acs.CategoryID,
sum(acs.Points),
t.Target
from
dbo.ActualCacheSale acs
inner join
(select
tb.UserID,
tb.RoleID,
tb.CategoryID,
sum(
(
(DATEDIFF(dd, (case when @start >= tb.StartDate then @start else tb.StartDate end), (case when @end <= tb.EndDate then @end else tb.EndDate end)) + 1)
) * tb.dailyMed
) as Target
from
dbo.TargetBucket tb
) t on
t.UserID = acs.UserID and
t.RoleID = acs.RoleID and
t.CategoryID = acs.CategoryID