2016-04-20 33 views
1

我有一张客户,产品,&等级的表格。该表格处于客户产品级别,每位客户最多可拥有5种产品。当有小于5级的产品,我想从另一个表中的数据来填充所以有5行数太少时填充 - Netezza SQL

原始表:

| Customer | Product | Rank | 
|----------|---------|------| 
| 123456 | 456  | 1 | 
| 123456 | 457  | 2 | 
| 123456 | 458  | 3 | 
| 234567 | 234  | 1 | 
| 234567 | 235  | 2 | 
| 234567 | 236  | 3 | 
| 234567 | 237  | 4 | 
| 234567 | 238  | 5 | 
| 345678 | 712  | 1 | 
| 345678 | 713  | 2 | 

填写表:

| Product | Rank | 
|---------|------| 
| 123  | 1 | 
| 124  | 2 | 
| 125  | 3 | 
| 126  | 4 | 
| 127  | 5 | 

结果我m寻找:

| Customer | Product | Rank | 
|----------|---------|------| 
| 123456 | 456  | 1 | 
| 123456 | 457  | 2 | 
| 123456 | 458  | 3 | 
| 123456 | 123  | 4 | 
| 123456 | 124  | 5 | 
| 234567 | 234  | 1 | 
| 234567 | 235  | 2 | 
| 234567 | 236  | 3 | 
| 234567 | 237  | 4 | 
| 234567 | 238  | 5 | 
| 345678 | 712  | 1 | 
| 345678 | 713  | 2 | 
| 345678 | 123  | 3 | 
| 345678 | 124  | 4 | 
| 345678 | 125  | 5 | 

编辑:我应该提到我想插入排名第一的行。所以,产品123应该是客户123456

回答

1

4级你可以用insert . . . select做到这一点:

insert into original(customer, product, rank) 
    select c.customer, f.product, f.rank 
    from (select distinct customer from original) c cross join 
     fillin f left join 
     original o 
     on o.customer = c.customer and o.rank = f.rank 
    where o.rank is null; 

您可以运行子查询,以获得缺失值。

这个想法是生成“填充”的所有可能的组合。然后删除那些已经有值的地方。

编辑:

哎呀,我还以为排名在表格填充是最后的排名。但你仍然可以这样做:

insert into original(customer, product, rank) 
    select c.customer, f.product, f.rank 
    from (select customer, max(rank) as maxrank from original) c cross join 
     fillin f left join 
     original o 
     on o.customer = c.customer and o.rank - o.maxrank + 1 = f.rank; 
+0

这太棒了,谢谢!我应该提到我想要插入排名第一的行。因此,产品123应该为顾客123456排名第4 – Adam12344