EDIT
Here is an example of my data:
create TABLE #Table
(
[Market] VARCHAR(100),
[Operator] VARCHAR(100),
[Date] DATE,
[Num Registrations] INT,
[Num Active] INT,
[Num Accepted Purchases] INT
)
INSERT INTO #Table VALUES
('Market1','Operator1','2012-12-01',2,4,7),
('Market1','Operator2','2012-12-01',3,5,7),
('Market1','Operator3','2012-12-01',1,2,7),
('Market2','Operator4','2012-12-01',2,1,7),
('Market2','Operator5','2012-12-01',0,4,7),
('Market3','Operator6','2012-12-01',2,44,7)
I have the following script:
SELECT
a.[Market],
a.[Operator],
a.[Date],
a.[Num Registrations],
a.[Num Active],
a.[Num Accepted Purchases],
[rnk] = b.rnk
FROM
#Table a
INNER JOIN
(
SELECT
[Market],
[rnk] = RANK() OVER (ORDER BY SUM([Num Registrations] + [Num Active]))
FROM #Table
GROUP BY [Market]
) b
ON
a.[Market] = b.[Market]
GROUP BY
a.[Market],
a.[Operator],
a.[Date],
a.[Num Registrations],
a.[Num Active],
a.[Num Accepted Purchases],
b.rnk
The above works ok but have I over-complicated things with the sub-query; could I have used the RANK function directly in the main query’s SELECT clause?
Yes, you don’t need to do an explicit join at all:
If you don’t have duplicates, then you can remove the
distinctfrom theselect.