Hi Brian,
The general idea is to use a subquery that counts, for each record, the
number of records for the same counsellor before the current record (in
the current sort order, of course).
Here's an example that works in the Northwind sample database. I'll
leave it to you to apply it to your own structure. It returns the order
details, sorted by OrderID and ProductID, with a sequential number that
starts at 1 for each OrderID:
SELECT
(SELECT COUNT(C.OrderID)
FROM [Order Details] AS C
WHERE C.OrderID = A.OrderID
AND C.ProductID <= A.ProductID) AS Seq,
A.OrderID,
A.ProductID,
A.UnitPrice,
A.Quantity
FROM [Order Details] AS A
ORDER BY A.OrderID, A.ProductID
;
If you only want to see the "surplus" records, repeat the subquery in a
WHERE clause, e.g. this, which shows the orders that include more than 5
items:
SELECT
(SELECT COUNT(C.OrderID)
FROM [Order Details] AS C
WHERE C.OrderID = A.OrderID
AND C.ProductID <= A.ProductID) AS Seq,
A.OrderID,
A.ProductID,
A.UnitPrice,
A.Quantity
FROM [Order Details] AS A
WHERE (SELECT COUNT(C.OrderID)
FROM [Order Details] AS C
WHERE C.OrderID = A.OrderID
AND C.ProductID <= A.ProductID) > 6
ORDER BY A.OrderID, A.ProductID;
Or if you want to see the "surplus" items but otherwise don't care about
the sequence, you can omit the first subquery, leaving
SELECT
A.OrderID,
A.ProductID,
A.UnitPrice,
A.Quantity
FROM [Order Details] AS A
WHERE (SELECT COUNT(C.OrderID)
FROM [Order Details] AS C
WHERE C.OrderID = A.OrderID
Actually, along the lines of counting rows, but a little different:
[quoted text clipped - 12 lines]
can't really use a "group by" for this, because I need to see each individual
record.