-- Define the CTE expression name and column list.
WITH Counter_CTE (SystemID, SystemName, ServerID, ServerName, SystemModel, SystemType, SystemGroup, RemsCode, City, Region)
AS
-- Define the CTE query.
(
select
sy.SystemID, sy.SystemName, se.ServerID, se.servername, smd.systemmodel, st.systemtype, sg.systemgroup, re.remscode, ci.city, co.region
from
Systems sy
inner join Servers se on sy.SystemID = se.systemid
inner join Systemmodels smd on sy.systemmodelid = smd.SystemModelID
inner join SystemTypes st on smd.SystemTypeID = st.SystemTypeID
inner join SystemGroups sg on st.SystemGroupID = sg.SystemGroupID
inner join REMS re on se.REMSID = re.REMSID
inner join Cities ci on re.CityID = ci.CityID
inner join Countries co on ci.CountryID = co.CountryID
--order by sy.SystemName
)
-- Define the outer query referencing the CTE name.
SELECT SystemID, region, COUNT(distinct SystemID) over (partition by systemid) AS TotalSsytems
FROM Counter_CTE
ORDER BY TotalSsytems desc
GO