我有一张名为tblEmployeeNominees的桌子,这张桌子是我们可以为一名雇员提供多名被提名人的雇员的被提名成员,我想显示该雇员的被提名成员的代号。 如果一名员工有两名被提名人,那么该员工的序列号必须显示为1,2 如果超过2或更多则必须显示1,2,3,..........
答案 0 :(得分:1)
SELECT *, ROW_NUMBER() OVER (PARTITION BY Employee ORDER BY Nominee)
FROM tblEmployeeNominees;
答案 1 :(得分:1)
看看这个。适用于sql server 2005
DECLARE @Table TABLE(
EmpID INT,
NomineeID INT
)
INSERT INTO @Table (EmpID,NomineeID) SELECT 1, 1
INSERT INTO @Table (EmpID,NomineeID) SELECT 1, 2
INSERT INTO @Table (EmpID,NomineeID) SELECT 2, 1
INSERT INTO @Table (EmpID,NomineeID) SELECT 3, 1
INSERT INTO @Table (EmpID,NomineeID) SELECT 3, 2
INSERT INTO @Table (EmpID,NomineeID) SELECT 3, 3
;WITH Serials AS (
SELECT EmpID,
MIN(NomineeID) MinNomineeID,
CAST(MIN(NomineeID) AS VARCHAR(MAX)) Serial
FROM @Table
GROUP BY EmpID
UNION ALL
SELECT t.EmpID,
t.NomineeID,
s.Serial + ',' + CAST(NomineeID AS VARCHAR(MAX)) Serial
FROM @Table t INNER JOIN
Serials s ON t.EmpID = s.EmpID
AND t.NomineeID > s.MinNomineeID
)
SELECT Serials.EmpID,
Serials.Serial
FROM Serials INNER JOIN
(
SELECT EmpID,
MAX(LEN(Serial)) LenSerial
FROM Serials
GROUP BY EmpID
) Lens ON Serials.EmpID = Lens.EmpID
WHERE LEN(Serials.Serial) = Lens.LenSerial
ORDER BY 1
OPTION (MAXRECURSION 0)