简体   繁体   中英

SQL Select Counter by Group

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

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

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

ORDER BY can have more than one clause

Try

SELECT Counter,EmpGroupID, EmpID
ORDER BY Counter,EmpGroupID, EmpID

Try this:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM