SQL 如何让某一列循环从1到5递增

如题所述

是查询结果中要求某一列循环从1到5递增? 可以使用row_number()函数给查询结果记录编号,然后整除5,余数为0的改为5即可。示例:

select s0.val, case when s0.idx = 0 then 5 else s0.idx end as idx
from (
 select s.val, row_number() over (order by val) % 5 as idx
 from (
  select 'a' as val
  union all select 'b'
  union all select 'c'
  union all select 'd'
  union all select 'e'
  union all select 'f'
  union all select 'g'
  union all select 'h'
  union all select 'i'
  union all select 'j'
  union all select 'k'
  union all select 'k'
  union all select 'l'
 ) s
) s0

 该查询在SQL Server 2005上通过;其他数据库方法类似即可。

如果是更新已有记录,则可以通过游标逐条更新。

温馨提示:答案为网友推荐,仅供参考
相似回答