我有一张桌子:
表1
isEnabled
我想使用一个序列为每个unique_id分配它。
我写了以下似乎无效的东西:
unique_id col_id val_id
1 100 a
1 101 b
1 102 c
1 103 d
2 106 a
2 106 b
2 104 c
2 103 d
输出为:
SELECT
my_seq.NEXTVAL over
(
PARTITION BY a.unique_id ORDER by a.unique_id) AS rec_i,
a.* FROM table1
a;
我如何使其工作?
答案 0 :(得分:1)
尝试一下:
-- data preparation
create table tt_table (unique_id number, col_id number, val_id varchar2(1));
insert into tt_table values(1,100,'a');
insert into tt_table values(1,101,'b');
insert into tt_table values(1,102,'c');
insert into tt_table values(1,103,'d');
insert into tt_table values(2,106,'a');
insert into tt_table values(2,104,'b');
insert into tt_table values(2,103,'c');
insert into tt_table values(2,103,'d');
-- creating function
CREATE OR REPLACE FUNCTION GET_SEQ RETURN NUMBER AS
BEGIN
RETURN TEJASH_SEQ.NEXTVAL;
END GET_SEQ;
/
--
-- actual query
--
WITH T2 AS (
SELECT /*+ materialize */
UNIQUE_ID,
GET_SEQ SEQ_VALUE
FROM
(
SELECT DISTINCT
UNIQUE_ID
FROM
TT_TABLE
) T2IN
)
SELECT
T1.UNIQUE_ID,
T1.COL_ID,
T1.VAL_ID,
T2.SEQ_VALUE
FROM
TT_TABLE T1,
T2
WHERE
T1.UNIQUE_ID = T2.UNIQUE_ID
ORDER BY
T1.UNIQUE_ID;
希望这会有所帮助。