以下是我为编写场景而编写的代码:
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的所有行都有counter = 1,groupid = 2000有counter = 2,groupid = 3000有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
答案 0 :(得分: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
答案 1 :(得分:4)
您的意思是,您需要一个使用逗号生成文本输出的查询?
尝试:
SELECT Counter + ',' + EmpGroupID + ',' + EmpID
FROM Table
ORDER BY EmpGroupID
答案 2 :(得分:3)
ORDER BY可以有多个子句
尝试
SELECT Counter,EmpGroupID, EmpID
ORDER BY Counter,EmpGroupID, EmpID
答案 3 :(得分:1)
根据你的描述猜测,你想要像
这样的东西吗? SELECT EmpGroupID,EmpID,COUNT(1)AS Counter
来自某些表名称
GROUP BY EmpGroupID,EmpID
ORDER BY COUNT(1),EmpGroupID,EmpID
这适用于SQL Server - 在其他情况下,您可以说
ORDER BY Counter,EmpGroupID,EmpID
答案 4 :(得分: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
答案 5 :(得分:1)
试试这个:
SELECT DENSE_RANK() OVER (ORDER BY EmpID) as 'counter',GroupID
FROM Emp
ORDER BY counter, EmpGroupID