0
這裏是我的表的所需輸出。只要每個組中不超過3個SegmentType並且每個組不超過15個記錄,則EmpID和SegmentType的順序無關緊要。每組3段,每組不超過15行
EmpID | WorkSegment | Group(What I'm trying to update) |
------| ----------- | --------------------------------- |
123 | yard | 1 |
245 | yard | 1 |
478 | yard | 1 |
584 | remote | 1 |
321 | remote | 1 |
879 | remote | 1 |
747 | office | 1 |
412 | office | 1 |
251 | office | 1 |
755 | support | 1 |
963 | support | 1 |
369 | support | 1 |
977 | intern | 1 |
888 | intern | 1 |
552 | intern | 1 |
225 | sales | 2 |
332 | sales | 2 |
357 | sales | 2 |
753 | yard | 2 |
這是我到目前爲止的代碼。這實現了每個組不超過3個WorkSegments的第一個目標,但現在我需要爲每個組添加一個僅限15行的限制。有任何想法嗎?
--Create table of distinct SegmentType
Select distinct SegmentType
into Work_DistinctSegmentTypes
from Work_AllData
Alter table Work_DistinctSegmentTypes
Add RowID INT IDENTITY(1, 1) NOT NULL
--Procedure to update group column
DECLARE @CurrentRowID INT,
@MaxRowID INT,
@SegmentType varchar(50)
SET @CurrentRowID = 1
SET @MaxRowID = (Select max(rowID) from Work_DistinctSegmentTypes)
WHILE @CurrentRowID <= @MaxRowID
BEGIN
Set @SegmentType = (Select SegmentType from Work_DistinctSegmentTypes Where RowID = @CurrentRowID)
Update Work_AllData
SET [Group] =(RowNum - (1))/3 + 1
FROM (SELECT EmpID,ROW_NUMBER() OVER (ORDER BY EmpID) AS RowNum
FROM Work_AllData
Where SegmentType = @SegmentType) st, Work_AllData
Where st.EmpID = Work_AllData.EmpID
SET @CurrentRowID = @CurrentRowID + 1
END
你能展示預期的產出嗎? –
嗨,歡迎來到SO。我們需要從您那裏得到更多信息,才能真正提供幫助。這是一個很好的開始。 http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ –
它看起來好像你需要添加一個Partition By語句你的行號,那麼你可以指出'RowNumber <= 15'的位置。 –