簡體   English   中英

在太少時填充行 - Netezza SQL

[英]Filling in Rows when Too Few - Netezza SQL

我有一張包含客戶、產品和排名的表格。 該表位於 Customer-Product 級別,每個客戶最多有 5 個產品。 當產品少於 5 個時,我想從另一個表中填寫數據,所以有 5 個。

原表:

| 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    |

我正在尋找的結果:

| 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 的排名 4

你可以用insert . . . select做到這一點insert . . . select insert . . . select 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM