我有一個名稱表,我想生成另一列「組」,每5個記錄增加1。以下是所需輸出的示例。5個記錄的SQL更新段
Name Group
Joe 1
Frank 1
Susan 1
Tom 1
Kim 1
Mike 2
John 2
Henry 2
Rick 2
Quinn 2
我有一個名稱表,我想生成另一列「組」,每5個記錄增加1。以下是所需輸出的示例。5個記錄的SQL更新段
Name Group
Joe 1
Frank 1
Susan 1
Tom 1
Kim 1
Mike 2
John 2
Henry 2
Rick 2
Quinn 2
創建CTE與行號將幫助
;WITH cte AS
(
SELECT
Name,
ROW_NUMBER() OVER (ORDER BY Name) AS RowNum
FROM YourTable
)
SELECT
Name,
(RowNum - 1)/5 + 1 AS [Group]
FROM cte
你可以嘗試這樣的事情
select a.name,
case when (a.myrow%5=0) then 5 else a.myrow%5 end as group
from
(select name,row_number() over (order by name) as myrow from YourTable)a
另一種方法
Create table #tmpNames
(
Name1 varchar(100)
)
Insert INTO #tmpNames
(Name1)
VALUES
('Joe'),
('Frank'),
('Susan'),
('Tom'),
('Kim'),
('Mike'),
('John'),
('Henry'),
('Rick'),
('Quinn')
Select Name1
,ROUND(rowCnt/6, 0, 1) + 1 as 'grp'
From (
Select
Name1
,ROW_NUMBER() over (order by Name1) as 'rowCnt'
From #tmpNames
) a
你使用什麼版本的SQL是?以及如何命令這些人爲了生成一個分組(需要一個我相信的命令)? –
我正在使用MS SQL Server 2014.它們可以按字母順序排列。 –