Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

postgresql - How to create a new column with a label for every 5 rows in sql?

I want to create a new column in my table. I want this new column to give the label "done" for every 5 rows.

My table looks like this:

no  type
1    a
2    a 
3    a
4    a
5    a
6    a 
7    a
8    a
9    a
10   a

and what I mean with the new column is:

no  type   flag
1    a    
2    a 
3    a
4    a
5    a      done
6    a 
7    a
8    a
9    a
10   a      done

so the "done" label will always appear for every 5 rows.

I use postgres for this. How can I do that with query?

Thanks in advance.

question from:https://stackoverflow.com/questions/65915916/how-to-create-a-new-column-with-a-label-for-every-5-rows-in-sql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the row_number() function and the modulo operator:

select no, type, 
       case 
         when row_number() over (order by no) % 5 = 0 then 'done'
       end as flag
from the_table
order by no;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...