diff --git a/server/datastore/mysql/software.go b/server/datastore/mysql/software.go index 61aa6b21bf..66a1356a41 100644 --- a/server/datastore/mysql/software.go +++ b/server/datastore/mysql/software.go @@ -314,12 +314,27 @@ func selectSoftwareSQL(hostID *uint, opts fleet.SoftwareListOptions) (string, [] } if opts.WithHostCounts { + subSelectCounts := dialect.From(goqu.I("aggregated_stats").As("shc")).Select( + "shc.id", "shc.json_value", "shc.updated_at", + ).Where(goqu.I("shc.type").Eq("software_hosts_count"), goqu.I("shc.json_value").Gt(0)). + SelectAppend( + goqu.I("shc.json_value").As("hosts_count"), + goqu.I("shc.updated_at").As("counts_updated_at"), + ) + subSelectListOpts := opts.ListOptions + switch subSelectListOpts.OrderKey { + case "hosts_counts", "counts_updated_at": + // all good, known columns, so we sort + subSelectCounts = appendListOptionsToSelect(subSelectCounts, opts.ListOptions) + default: + // we don't sort if it's not a column from this table + } ds = ds.Join( - goqu.I("aggregated_stats").As("shc"), + subSelectCounts.As("shc"), goqu.On( goqu.I("s.id").Eq(goqu.I("shc.id")), ), - ).Where(goqu.I("shc.type").Eq("software_hosts_count"), goqu.I("shc.json_value").Gt(0)). + ). SelectAppend( goqu.I("shc.json_value").As("hosts_count"), goqu.I("shc.updated_at").As("counts_updated_at"),