您的位置:首页 > 其它

Teradata中排名和序列字段实现

2012-07-09 10:20 351 查看
需求一:根据某字段产生排名字段:

原表数据如下:

sel statistics_dt,count_num from dwPDATA.fanxiaoliang_unittest;

2009-01-02 4

2009-01-02 6

2009-01-02 6

2009-01-02 7

2009-01-02 9

生成一个根据某字段排名的字段,下例中对某statistics_dt内的count_num实现排名,有两种方法,但是这两种方法不能实现并列排名,如下:

sel row_number() over ( partition by statistics_dt order by count_num),count_num from dwPDATA.fanxiaoliang_unittest;

1 4

2 6

3 6

4 7

5 9

sel csum(1,count_num),count_num from dwPDATA.fanxiaoliang_unittest group by statistics_dt;

1 4

2 6

3 6

4 7

5 9

注:CSUM(n,count_num)的作用是根据对count_num字段升序产生一个序列,这个序列以n开始,依次往上累计,例如CSUM(1,count_num)就是根据count_num排序,产生一个排序字段。

sel csum(2,count_num desc),count_num from dwPDATA.fanxiaoliang_unittest

2 9

4 7

6 6

8 6

10 4

要实现并列排名,可以使用下面两种方法,但是下面两种方法实现的排名是有区别的,第一种并列也占排名里的一个位置,如下:

sel rank() over ( partition by statistics_dt order by count_num),count_num from dwPDATA.fanxiaoliang_unittest;

1 4

2 6

2 6

4 7

5 9

第二种方法并列的不占用一个排名,如下:

temp1:

sel csum(1,a.count_num) as paim,a.count_num from

(sel  count_num from dwPDATA.fanxiaoliang_unittest

qualify row_number() over ( partition by count_num order by count_num) = 1)a;

update aa

from temp aa,temp1 bb

set paim = bb.paim

where aa.count_num = bb.count_num;

1 4

2 6

2 6

3 7

4 9

需求二:产生一个序列字段,当此字段不插入值时根据事先定义好的数据范围产生一个序列值。

下面是建表,CC字段就是一个序列字段:

DROP TABLE dwpdata.aa_fan;

CREATE SET TABLE dwPDATA.aa_fan ,NO FALLBACK ,

     NO BEFORE JOURNAL,

     NO AFTER JOURNAL,

     CHECKSUM = DEFAULT

     (

      cc INTEGER GENERATED ALWAYS AS IDENTITY

           (START WITH 5

            INCREMENT BY 2

            MINVALUE -2147483647

            MAXVALUE 2147483647

            NO CYCLE),

      aa CHAR(1) CHARACTER SET LATIN NOT CASESPECIFIC)

PRIMARY INDEX ( cc );

插入测试值:

insert into dwpdata.aa_fan values('','g');

insert into dwpdata.aa_fan values('','3');

insert into dwpdata.aa_fan values('','d');

查看表中数据,cc字段根据设定好的方式自动插入:

sel * from dwpdata.aa_fan;

5 g
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息