SQL - 有效地将两个查询连接在一起

Ric*_*ick 0 sql sql-server

我有两个SQL查询查询不同的表并返回类似的字段:

User - Role - Category - Points
Run Code Online (Sandbox Code Playgroud)

User - Role - Category - Target
Run Code Online (Sandbox Code Playgroud)

我的查询看起来像这样:

select
    acs.UserID,
    acs.RoleID,
    acs.CategoryID,
    sum(acs.Points)
from acs
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我想最终得到的是这样的:

User - Role - Category - Points - Target
Run Code Online (Sandbox Code Playgroud)

每个单独的查询运行时间不到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
Run Code Online (Sandbox Code Playgroud)

aut*_*tic 6

尝试

select
aa.UserId,
aa.Roleid,
aa.CategoryId
Sum(aa.Points) as Points,
Sum(aa.Target) as Target
from
(
select
    acs.UserID,
    acs.RoleID,
    acs.CategoryID,
    sum(acs.Points) as Points
    null as target
from acs

union all

select
    tb.UserID,
    tb.RoleID,
    tb.CategoryID,
    0 as points
    sum(
        (
        (DATEDIFF(dd, (case when @start >= tb.StartDate then @start else tb.StartDatee end),     
    (case when @end <= tb.EndDate then @end else tb.EndDate end)) + 1) 
    ) * tb.dailyMed
    ) as Target
from tb) as aa
group by
aa.UserId,
aa.Roleid,
aa.CategoryId
Run Code Online (Sandbox Code Playgroud)