从具有最大日期的多个联接中聚合

时间:2019-10-16 19:22:43

标签: sql tsql aggregate

3张桌子

<h>DesktopGroup</h>
<table style="undefined;table-layout: fixed; width: 81px"><colgroup><col style="width: 25px"><col style="width: 55.5px"></colgroup><tr><th>id</th><th>name</th></tr><tr><td>1</td><td>group1</td></tr><tr><td>2</td><td>group2</td></tr></table>

<h>machines</h>
<table style="undefined;table-layout: fixed; width: 198px"><colgroup><col style="width: 31px"><col style="width: 67px"><col style="width: 99.5px"></colgroup><tr><th>id</th><th>name</th><th>Desktopgroupid</th></tr><tr><td>1</td><td>server1</td><td>1</td></tr><tr><td>2</td><td>server2</td><td>1</td></tr><tr><td>3</td><td>server3</td><td>2</td></tr></table>

<h>loadindex</h>
<table style="undefined;table-layout: fixed; width: 456px"><colgroup><col style="width: 28px"><col style="width: 61px"><col style="width: 89px"><col style="width: 277.5px"></colgroup><tr><th>id</th><th>load</th><th>machineid<br></th><th>Createdate</th></tr><tr><td>1</td><td>7654</td><td>1</td><td>2019-10-15 16:54:31.430</td></tr><tr><td>2</td><td>1235</td><td>1</td><td>2019-10-15 16:44:00.430</td></tr><tr><td>3</td><td>4443</td><td>1</td><td>2019-10-15 16:34:31.000</td></tr><tr><td>4</td><td>2345</td><td>1</td><td>2019-10-15 16:25:15.222</td></tr><tr><td>5</td><td>3456</td><td>2</td><td>2019-10-15 16:54:31.430</td></tr></table>
每个桌面组具有x个服务器,并且每个服务器都有给定的时间点负载。 (大约每5分钟) 所以我想要得到的 desktopgroup.name,组中所有计算机的avg(load),以max(date)表示负载。

select loadvalues.avgload, dg.Name
from CitrixMonitoring.DesktopGroups as dg
join CitrixMonitoring.Machines as m on m.DesktopGroupId = dg.id
join (select LoadIndex.MachineId, avg(LoadIndex.EffectiveLoadIndex) as avgload, max(LoadIndex.[CreatedDate]) as maxdate
from CitrixMonitoring.LoadIndex group by MachineId) as [loadvalues] on m.id = loadvalues.MachineId
where dg.name like 'live - call center desktop'
group by dg.name, loadvalues.avgload

我知道

3185    LIVE - Call Center Desktop
3236    LIVE - Call Center Desktop
3249    LIVE - Call Center Desktop
3263    LIVE - Call Center Desktop
3288    LIVE - Call Center Desktop
3295    LIVE - Call Center Desktop

预期结果应为一列,并且桌面组平均加载

3185    LIVE - Call Center Desktop

1 个答案:

答案 0 :(得分:0)

GROUP BY dg.name。当您在loadvalues.avgload子句中包含GROUP BY时,这意味着您要为avgload的每个不同值单独分配一行。

但是由于您只是在dg.name子句中选择了一个WHERE,所以根本不需要GROUP BY。所以应该就是这样。

select loadvalues.avgload, loadvalues.maxdate, dg.Name
from CitrixMonitoring.DesktopGroups as dg
join CitrixMonitoring.Machines as m on m.DesktopGroupId = dg.id
join (select LoadIndex.MachineId, avg(LoadIndex.EffectiveLoadIndex) as avgload, max(LoadIndex.[CreatedDate]) as maxdate
from CitrixMonitoring.LoadIndex group by MachineId) as [loadvalues] on m.id = loadvalues.MachineId
where dg.name like 'live - call center desktop'