2

这是我为创建场景而编写的代码:

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

我需要的是每个组都有一个计数器变量,以 1 递增,这样第 1000 组的所有行的计数器 = 1,groupid = 2000 的计数器 = 2,groupid = 3000 的计数器 = 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
4

6 回答 6

5

您正在描述密集的组排名:

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

这里有一些参考资料:http: //msdn.microsoft.com/en-us/library/ms189798.aspx

于 2009-06-01T20:12:16.297 回答
4

您的意思是,您需要一个使用逗号生成文本输出的查询,如图所示?

尝试:

SELECT Counter + ',' + EmpGroupID + ',' + EmpID
FROM Table
ORDER BY EmpGroupID
于 2009-06-01T19:27:55.950 回答
3

ORDER BY 可以有多个子句

尝试

SELECT Counter,EmpGroupID, EmpID
ORDER BY Counter,EmpGroupID, EmpID
于 2009-06-01T19:26:27.730 回答
1

根据您的描述猜测,您是否想要类似的东西

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

这适用于 SQL Server - 在其他情况下,您可能会说

ORDER BY Counter, EmpGroupID, EmpID

于 2009-06-01T19:27:47.433 回答
1

我花了一段时间才明白你在问什么。据我了解,您想根据 EmpGroupID 创建和填充“计数器”列吗?如果是这样,那么是这样的:

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
于 2009-06-01T19:30:12.280 回答
1

试试这个:

SELECT DENSE_RANK() OVER (ORDER BY EmpID) as 'counter',GroupID 
FROM Emp
ORDER BY counter, EmpGroupID
于 2009-08-14T14:34:06.470 回答