tags:

views:

611

answers:

6

Here is the code I've written to create a scenario:

USE tempdb
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.Emp') AND type in (N'U'))
DROP TABLE Emp
GO
CREATE TABLE Emp(
EmpID Int Identity(10,1) Primary Key,
EmpGroupID Int)
GO
INSERT INTO Emp(EmpGroupID) VALUES(1000)
INSERT INTO Emp(EmpGroupID) VALUES(1000)
INSERT INTO Emp(EmpGroupID) VALUES(1000)
INSERT INTO Emp(EmpGroupID) VALUES(2000)
INSERT INTO Emp(EmpGroupID) VALUES(2000)
INSERT INTO Emp(EmpGroupID) VALUES(2000)
INSERT INTO Emp(EmpGroupID) VALUES(3000)
GO
SELECT * FROM Emp
ORDER BY EmpGroupID,EmpID

What I need is for each group to have a counter variable, incrementing by 1, such that all the rows for Group 1000 have counter=1, groupid=2000 has counter=2, groupid=3000 has counter=3.

SELECT ?,EmpID,EmpGroupID 
FROM Emp
ORDER BY EmpGroupID,EmpID
-- The result I'm looking for is:
1,10,1000
1,11,1000
1,12,1000
2,13,2000
2,14,2000
2,15,2000
3,16,3000
+3  A: 

ORDER BY can have more than one clause

Try

SELECT Counter,EmpGroupID, EmpID
ORDER BY Counter,EmpGroupID, EmpID
Malfist
That is if you want it in, Counter -> EmpGroupID -> EmpID, if you want it in Counter -> EmpID -> EmpGroupID just swap the last two values.
Malfist
+1  A: 

Guessing from your description, do you want something like

SELECT EmpGroupID, EmpID, COUNT(1) AS Counter
FROM some-table-name
GROUP BY EmpGroupID, EmpID
ORDER BY COUNT(1), EmpGroupID, EmpID

That's for SQL Server - in other cases you may be able to say

ORDER BY Counter, EmpGroupID, EmpID

le dorfier
I apologize for not making it clear that Counter wasn't in table.
cf_PhillipSenn
What exactly are you counting? Please update your question so we can help you find an answer.
Malfist
+3  A: 

You mean, you need a query that produces textual output with the commas as shown?

Try:

SELECT Counter + ',' + EmpGroupID + ',' + EmpID
FROM Table
ORDER BY EmpGroupID
Michael Petrotta
+1  A: 

It took me a while to understand what you were asking. As I understand it, you want to create and populate the 'Counter' column based on the EmpGroupID? If so, then something like this:

SELECT EmpGroupID, EmpID,
    (SELECT COUNT(*) +1 
     FROM [table] 
     WHERE t2.EmpGroupID < t1.EmpGroupID GROUP BY t2.EmpGroupID
    ) AS Counter
FROM [table] t1
ORDER BY EmpGroupID, EmpID
Joel Coehoorn
+3  A: 

You're describing a dense ranking of groups:

SELECT
  DENSE_RANK() OVER (ORDER BY EmpGroupID) as Counter,
  EmpID,
  EmpGroupID
FROM Emp
ORDER BY EmpGroupID,EmpID

And here's some reference material: http://msdn.microsoft.com/en-us/library/ms189798.aspx

David B
Well, I learned something new. Here I was, trying to hack something up with number tables...
Michael Petrotta
+1  A: 

SELECT DENSE_RANK() OVER (ORDER BY EmpID) as 'counter',GroupID FROM Emp ORDER BY counter, EmpGroupID

Rodrigo Lins
SELECT DENSE_RANK() OVER (ORDER BY EmpGroupID) as 'counter',EmpGroupID FROM Emp ORDER BY counter, EmpGroupID
cf_PhillipSenn