I have 2 table like below,
product1 item1 rank1
1234 XXXX 1
1234 YYYY 2
5678 GGGG 3
5678 HHHH 4
product2 item2 score rank2
1234 XXXX 90 1
1234 ZZZZ 80 2
1234 YYYY 70 3
1234 CCCC 60 4
5678 HHHH 80 1
5678 GGGG 60 2
5678 DHDH 50 3
9800 AAAA 100 1
4352 BBBB 45 1
I need the output of table 2 to be changed like below,
product2 item2 score rank2
1234 XXXX 90 1
1234 YYYY 70 2
1234 ZZZZ 80 3
1234 CCCC 60 4
5678 GGGG 60 1
5678 HHHH 80 2
5678 DHDH 50 3
9800 AAAA 100 1
4352 BBBB 45 1
The below SQL provides the below output,
SELECT PRODUCT2,LINE2,SCORE,ROWNUMBER()
OVER (Partition by PRODUCT1 order by A.RANK1 ) RANK
FROM TABLE1 A, TABLE2 B WHERE A.ITEM1= B.ITEM2 AND
A.PRODUCT1 = B.PRODUCT2
UNION ALL
SELECT PRODUCT2,LINE2,SCORE,
ROWNUMBER() OVER (Partition by PRODUCT2 ORDER BY SCORE DESC) RANK
FROM TABLE2 C
WHERE NOT EXISTS (
SELECT * FROM TABLE1 A WHERE A.PRODUCT1 = C.PRODUCT2
AND A.ITEM1= C.ITEM2)
product2 item2 score rank2
1234 XXXX 90 1
1234 YYYY 70 2
1234 ZZZZ 80 1
1234 CCCC 60 2
5678 GGGG 60 1
5678 HHHH 80 2
5678 DHDH 50 1
9800 AAAA 100 1
4352 BBBB 45 1
The lines which are not available in table1 are not getting the increment rank after the comparison of table2 but instead of that they are getting the new rank starting it as 1. can someone please look into this and advise me on how to achieve the expected results in db2 ?
Input :
Table 1:
Product1 item1 rank1
12345 Xxxx 1
12345 yyyyy 2
12345 Cccc 3
67890 Aaaa 4
Table2:
Product2. Item2 score rank2
12345 Bbbb 90 1
12345 yyyyy 80 2
12345 Xxxx 70 3
12345 Cccc 60 4
67890 Aaaa 95 1
67890 Bbbb 85 2
56789 Ghsg 67 1
45377 Hhhh 70 1
Expected output :
Product2. Item2. Score. Rank
12345 Xxxx 70 1
12345 yyyyy 80 2
12345 Cccc 60 3
12345 Bbbb 90 4
67890 Aaaa 95 1
67890 Bbbb 85 2
56789 Ghsq 67 1
45377 Hhhh 70 1
答案 0 :(得分:0)
SELECT PRODUCT2, LINE2, SCORE,
CASE WHEN A_ITEM1 IS NULL THEN RANK2 ELSE RANK END AS RANK
FROM (
SELECT PRODUCT2, LINE2, SCORE,
A.ITEM1 A_ITEM1,
ROWNUMBER() OVER (Partition by PRODUCT1 order by A.RANK1 AS RANK,
ROWNUMBER() OVER (Partition by PRODUCT2 order by B.SCORE AS RANK2
FROM TABLE1 B
LEFT JOIN TABLE1 A ON A.ITEM1 = B.ITEM2 AND A.PRODUCT1 = B.PRODUCT2
) Z
答案 1 :(得分:-1)
试试这个:
with t1 as (
select f1.*, rownumber() over(partition by f1.Product1 order by f1.rank1) rank
from table1 f1
),
t2 as (
select f1.*, rownumber() over(partition by f1.Product2 order by f1.score desc) rank
from table2 f1
)
select t2.Product2, ifnull(t1.item2, t2.item2) item2, t2.score, t2.rank as rank
from t2 left outer join t1 on t1.Product1=t2.Product2 and t1.rank=t2.rank