我有一个名为machineStatus的表:
ID Successfiles totaldata Backupsessiontime
> 1 3 988 1256637314
> 2 21 323 1256551419
> 3 8 23 1256642968
> 4 94 424 1256642968
> 1 42 324 1256810937
> 1 0 433 1256642968
现在我想在ID中对成功文件和总数据进行总结,但只显示最新的Backupsessiontime。 我可以单独做但不能一起做。 任何建议????
单独这样做:
获得总和:
select ID, sum(NumOfSuccessFiles), sum(TotalData)
from MachineStat
group by ID;
获取最新消息:
With idT as (
select ID
from MachineStat
group by ID
)
select applyT.*
from idT p
CROSS APPLY (
select top 1 ID,BackupSessionTime from MachineStat where eID=p.ID
order by MachineID desc
) as applyT
答案 0 :(得分:3)
您可以使用适合您需要的聚合函数:
select
ID,
sum(NumOfSuccessFiles) TotalNumOfSuccessFiles,
sum(TotalData) TotalData,
max(Backupsessiontime) LastBackupsessiontime
from
MachineStat ms
group by
ID
如果您需要更复杂的排序逻辑,也可以在主查询中使用子查询。
select
ID,
sum(NumOfSuccessFiles) TotalNumOfSuccessFiles,
sum(TotalData) TotalData,
(select top 1 Backupsessiontime from MachineStat where ID = ms.ID order by ...) LastBackupsessiontime
from
MachineStat ms
group by
ID
答案 1 :(得分:3)
看起来你想要做
select ID, sum(NumOfSuccessFiles), sum(TotalData), max(Backupsessiontime)
from MachineStat
group by ID;
答案 2 :(得分:0)
Max(BackupSessionTime)?