Here's one way:declare @department table (dID int, department varchar(20))insert @departmentselect 800, 'tiles' union allselect 900, 'plumbing' union allselect 1000, 'paint'declare @supplier table (sID varchar(5), supplier varchar(20))insert @supplierselect 'G000', 'CTM' union allselect 'K000', 'caroma' union allselect 'Z000', 'dulux'declare @Associations table (aID int, dID int, sID varchar(5))insert @associationsselect 7001, 800, 'G000' union allselect 7002, 900, 'K000' union allselect 7003, 1000, 'Z000' union allselect 7004, 800, 'Z000' union allselect 7005, 900, 'G000'declare @spenditure table (aID int, total int)insert @spenditureselect 7001, 5000 union allselect 7002, 8500 union allselect 7003, 3200 union allselect 7004, 4650 union allselect 7005, 2100select s.sID ,max(e.total) AS total ,max(ca.department) as department --min / max doesn't matter because of group by in cross applyfrom @supplier sjoin @associations a on a.sid = s.sidjoin @spenditure e on e.aID = a.aIDcross apply ( select top 1 d1.department from @supplier s1 join @associations a1 on a1.sID = s1.sID join @spenditure e1 on e1.aID = a1.aID join @department d1 on d1.dID = a1.dID where a1.sID = s.sID group by d1.department order by sum(e1.total) desc ) caGROUP by s.sIDORDER BY s.sID OUTPUT:sID total department----- ----------- --------------------G000 5000 tilesK000 8500 plumbingZ000 4650 tiles
Be One with the OptimizerTG