How to create some kind of iterator (or artificial id) for a given set of rows?

房东的猫 提交于 2020-01-05 16:53:15

问题


Sorry for the dumb title, but I simply don't know how to call it.

Here's what I want. Look at the following query:

SELECT *
FROM (
  SELECT xyz
)
JOIN ...
ORDER BY RANDOM()

I want to know the initial order of the xyz rows when the query is over. So I thought about something like this (pseudo SQL):

iterator = 1;
SELECT *
FROM (
  SELECT iterator++, xyz
)
JOIN ...
ORDER BY RANDOM()

So afterwards my result set will look like this:

iterator | some other data
--------------------------
5        | ...
1        | ...
6        | ...
8        | ...
4        | ...
2        | ...
7        | ...
3        | ...

So it would afterwards be possible to recreate the original order.

May you will now say: Why you don't simply use the id where you select xyz? Simple: There's no id. The xyz data is user input and I want to create an artificial id for that within the query.

Thank you.


回答1:


You should be able to use row_number() (which is a windowing function) to assign the "iterator" that you want. This will create a sequenced number for each row:

select *
from
(
  select col,
     row_number() over(order by col) rn
  from yourtable
) src
order by random()

See SQL Fiddle with Demo




回答2:


The SQL standard way would be:

select row_number() over (order by random()) as seqnum
from (your query goes here) t
order by 1

This uses the window function row_number() as your "iterator". It then returns the rows in the order specified.



来源:https://stackoverflow.com/questions/15126254/how-to-create-some-kind-of-iterator-or-artificial-id-for-a-given-set-of-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!