SQL 合并 MAX 和 SUM

SQL Combining MAX and SUM

所以我有一个 SQL table 包含以下列:

License# - int
Name - char(255)
ActivityDate - datetime
FundsIn - money,null

大约有 2800 个唯一的许可证号,每天都会有大量的资金。我试图找到 activity (ActivityDate) 的最后日期以及该 MAX ActivityDate 上所有 FundsIn 的总和。

下面是我一直试图修改以使其正常工作的查询,但它 return 是所有日期的许可证号总和,而不仅仅是最大日期。

Select License, Name, MAX(ActivityDate), FundsIn
From (
    Select License, Name, ActivityDate, SUM(FundsIn) as Funds_In
    From Table1
    group by License, Name, ActivityDate
) foo
group by License, Name, FundsIn

我知道当前查询的问题在于它对 FundsIn 的整个数据集进行了分组,但我不知道如何将 FundsIn 的总和限制为仅 MAX 日期。任何帮助将不胜感激。

采样日期

License   Name   ActivityDate   FundsIn
123       A      8/29/2020      40
123       A      8/29/2020      60
123       A      8/29/2020      80
123       A      8/29/2020      55
123       A      8/30/2020      10
123       A      8/30/2020      15
123       A      8/30/2020      12
123       A      8/30/2020      60
123       A      8/30/2020      70
234       B      8/29/2020      12
234       B      8/29/2020      15
234       B      8/29/2020      19
234       B      8/29/2020      22
234       B      8/29/2020      33
234       B      8/30/2020      13
234       B      8/30/2020      78
234       B      8/30/2020      28
234       B      8/30/2020      34
234       B      8/30/2020      46

在上面的数据中,查询将return下面的

License   Name   ActivityDate   FundsIn
123       A      8/30/2020      167
234       B      8/30/2020      199

我想你正在寻找这样的东西。 CTE 使用 row_number 来查找每个许可证的最大 ActivityDate。然后 CTE 在 License 和 ActivityDate(最大)加入回 Table1。

;with max_cte as (
    select *, row_number() over (partition by License order by activityDate desc) rn from Table1 t)
Select License, Name, ActivityDate, SUM(FundsIn) as Funds_In
From max_cte mc
     join Table1 t on mc.License=t.License
                      and mc.ActivityDate=t.ActvityDate
where mc.rn=1
group by License, Name, ActivityDate;

我了解到您想要每个许可最近activity日期的资金总额(并非所有许可可能每天都处于活动状态)。

有多种表达方式。一种方法是具有相关子查询的过滤器:

select license, name, activityDate, sum(fundsIn) fundsIn
from mytable t
where t.activityDate = (select max(t1.activityDate) from mytable t1 where t1.license = t.license)
group by license, name, activityDate

在其他选项中,一个更奇特的选择是 order bytop (1) with ties:

select top (1) with ties license, name, activityDate, sum(fundsIn) fundsIn
from mytable t
group by license, name, activityDate
order by row_number() over(partition by license order by activityDate desc) 

我希望第二种方法在大型数据集上效率较低。