使用SQL将记录按3或n值平均分组

时间:2018-12-14 02:37:53

标签: sql sql-server

如何在SQL中将记录平均除以3。请参考以下示例。

DocNos   SiteCode  SiteName   
11111    0001      Canada
11111    0002      Australia
11111    0003      China
11111    0004      Japan
11111    0005      India
11111    0006      Brazil
11111    0007      England
11111    0008      Italy

所需的输出

DocNos   SiteCode  SiteName     Group
11111    0001      Canada        1
11111    0002      Australia     1
11111    0003      China         1
11111    0004      Japan         2
11111    0005      India         2
11111    0006      Brazil        2
11111    0007      England       3
11111    0008      Italy         3

2 个答案:

答案 0 :(得分:2)

通过某种算术使用类似row_number的函数。根据所需的组大小更改分母。

select t.*,1+(row_number() over(partition by docnos order by sitecode)-1)/3 as grp
from tbl t

答案 1 :(得分:1)

我建议使用NTILE()窗口函数:

SELECT
  *,
  NTILE() OVER(ORDER BY DocNos, SiteCode, SiteName) AS Grp
FROM table;

另一种方式,使用CTE(公用表表达式)和ROW_NUMBER()

WITH total_rows AS (
  -- Count total rows
  SELECT COUNT(*) row_count
  FROM table
)
SELECT
  *,
  CAST(ROW_NUMBER() OVER(ORDER BY DocNos, SiteCode, SiteName) / row_count) AS INT) AS Grp
FROM table
CROSS JOIN total_rows;

进一步阅读: