我很难在SQL Server 2008中获取各种记录的最新结果。我正在尝试使用MAX(),但只有在应该超过1,000时才会返回一些结果。
编辑:结果包括计算机名称和上次使用信息。它适用于SCCM的软件计量结果。 “mf.SecurityKey ='CSA00107'”这一行基本上只是在寻找Microsoft Visio的软件计量结果。但是,每台计算机都有“上次使用”日期的各种实例。我需要最后的“上次使用”日期,因此每个计算机名称都有最后一个使用记录。
查询:
select distinct vrs.Name0,mus.LastUsage
from v_MeteredFiles mf
inner join v_MonthlyUsageSummary mus on mus.FileID = mf.MeteredFileID
left outer join v_R_System vrs on vrs.ResourceID = mus.ResourceID
where mf.SecurityKey = 'CSA00107' and
DateDiff(day, mus.LastUsage, GetDate()) > 60 and
mus.LastUsage in (select max(LastUsage) from v_MonthlyUsageSummary group by ResourceID)
当我删除最后一行时,我会收到所有结果。但是,由于单个“Name0”有各种“LastUsage”记录,因此我得到的结果太多了。我需要每台机器的最新LastUsage。任何帮助将不胜感激。
答案 0 :(得分:2)
您可以使用row_number
功能代替sub-query
。
select Name0, LastUsage
from (
select vrs.Name0, mus.LastUsage,
row_number() over(partition by vrs.Name0 order by mus.lastusage desc) as rn
from v_MeteredFiles mf
inner join v_MonthlyUsageSummary mus on mus.FileID = mf.MeteredFileID
left outer join v_R_System vrs on vrs.ResourceID = mus.ResourceID
where mf.SecurityKey = 'CSA00107' and
DateDiff(day, mus.LastUsage, GetDate()) > 60 ) t
where rn = 1;
编辑:根据评论中的OP请求
select Name0, LastUsage
from (
select vrs.Name0, mus.LastUsage,
row_number() over(partition by vrs.Name0 order by mus.lastusage desc) as rn
from v_MeteredFiles mf
inner join v_MonthlyUsageSummary mus on mus.FileID = mf.MeteredFileID
left outer join v_R_System vrs on vrs.ResourceID = mus.ResourceID
where mf.SecurityKey = 'CSA00107' ) t
where rn = 1
and DateDiff(day, LastUsage, GetDate()) > 60
答案 1 :(得分:0)
我认为您应该将in
替换为=
内部选择需要参考外部值。
select distinct vrs.Name0,mus.LastUsage
from v_MeteredFiles mf
inner join v_MonthlyUsageSummary mus
on mus.FileID = mf.MeteredFileID
left outer join v_R_System vrs
on vrs.ResourceID = mus.ResourceID
where mf.SecurityKey = 'CSA00107'
and DateDiff(day, mus.LastUsage, GetDate()) > 60
and mus.LastUsage **=** (select max(LastUsage)
from v_MonthlyUsageSummary IMUS
**where IMUS.ResourceID = mus.ResourceID**)