Oracle查询用于从表中选择数值的采样

时间:2017-03-29 20:09:42

标签: sql oracle

我的Oracle数据库表中有一个数据字段,其数据类型为NUMBER。我在下面使用order by尝试了一个查询。

SELECT Value
  FROM Table
 ORDER BY value;

我的结果是

Value |
------|
1     |
1     |
2     |
2     |
3     |
3     |
4     |
4     |
5     |
5     |
6     |
6     |

相反,我想要一个结果

Value |
------|
1     |
2     |
3     |
4     |
5     |
6     |
1     |
2     |
3     |
4     |
5     |
6     |

3 个答案:

答案 0 :(得分:2)

您可以使用row_number来评估值的出现是第一个,第二个,等等;基于此值的order by,然后表中的值将完成工作。

例如:

/* a test case */
with someTable(value) as (
    select 1 from dual union all
    select 2 from dual union all
    select 3 from dual union all
    select 4 from dual union all
    select 5 from dual union all
    select 6 from dual union all
    select 1 from dual union all
    select 2 from dual union all
    select 3 from dual union all
    select 4 from dual union all
    select 5 from dual union all
    select 6 from dual 
)
/* the query */
select value
from someTable
order by row_number() over ( partition by value order by null), value

工作原理:

select value, row_number() over ( partition by value order by null) rowNumber
from someTable
order by row_number() over ( partition by value order by null), value

给出:

     VALUE  ROWNUMBER
---------- ----------
         1          1
         2          1
         3          1
         4          1
         5          1
         6          1
         1          2
         2          2
         3          2
         4          2
         5          2
         6          2

答案 1 :(得分:1)

请试试这个。我使用ROW_NUMBER()根据它们的出现次数排列值,

SELECT VALUE
FROM (
  SELECT VALUE
    , ROW_NUMBER() OVER (PARTITION BY VALUE ORDER BY VALUE ASC) RNK
  FROM MY_TABLE
)
ORDER BY RNK
  , VALUE;

答案 2 :(得分:0)

1值| ------ | 1 | 1 | 2 | 2 | 3 | 3 | 4 | 4 | 5 | 5 | 6 | 6 |

SELECT ROW_NUMBER() OVER (PARTITION BY VALUE ORDER BY VALUE) AS RN, TABLE  .* FROM TABLE   

2值| ------ | 1 | 2 | 3 | 4 | 5 | 6 | 1 | 2 | 3 | 4 | 5 | 6 |

SELECT ROWNUM,TABLE.* FROM TABLE