我有这些记录,我想创建一个oracle select查询来生成以1,2,3为值的虚拟列。请帮助谢谢。
field1
one
two
three
four
five
six
seven
eight
基本上我想添加值为1到3的虚拟列。一旦达到3,它就会再次回到1。
field1 dummycol
one 1
two 2
three 3
four 1
five 2
six 3
seven 1
eight 2
答案 0 :(得分:1)
一种简单的方法是使用rownum
伪列和mod
函数:
select field1, mod(rownum - 1, 3) + 1
from <your table>;
但是,如果查询has an order-by clause,甚至是in a subquery,并且大概你想要的话确实需要强加一些命令并且循环号码与之结合,那么这并不像预期的那样有效最终订单。
您可以使用分析row_number()
功能代替:
select field1,
mod(row_number() over (order by null) - 1, 3) + 1 as dummycol
from <your table>
order by field1;
FIELD1 DUMMYCOL
---------- --------
eight 1
five 2
four 3
one 1
seven 2
six 3
three 1
two 2
答案 1 :(得分:0)
您在此处使用的机制是将固定值包含为命名列,例如
select '1' as one
对于您的情况,请使用
之类的内容select '1' as one, '2' as two, '3' as three, '1' as four, '2' as five, '3' as six, '1' as seven, '3' as eight
当您构建多个查询的联合并希望结果指示有关每个源的内容时,此机制通常会发挥作用,例如
select name, date, 'student' as Type from student
union
select name, date, 'teacher' as Type from teacher
union
select name, date, 'alumni' as Type from alumni