英文:
SQL problem to select value based on priority
问题 {#heading}
我有一个名为Table1的表格
| 唯一标识 | 列 B | 列 C | 列 D | |------|-----|-----|-----| | 1 | A | 第二 | abc | | 2 | A | 第一 | def | | 3 | A | 第二 | ghi |
这是Table2
| 排名 | 值 | |----|----| | 1 | 第一 | | 2 | 第二 | | 3 | 第三 |
现在我需要按照以下方式选择值,条件将基于Table1的列C,并根据Table2进行选择。
就像在上面的表1中,列C有三个值(第二,第一,第一),但根据Table2,第一排名优于第二,因此我的输出应该与之前的相同。
基本上,我必须基于排名选择优越的值。如果Table1的列C有(第三,第二,第二),那么我想选择第二个,如果Table1的列C有(第三,第二,第一),那么我想选择第一个。如果所有三个值都相同,那么将选择它。
| 唯一标识 | 列 B | 列 C | 列 D | 列 D | |------|-----|-----|-----|-----| | 1 | A | 第二 | abc | 第一 | | 2 | A | 第一 | def | 第一 | | 3 | A | 第二 | ghi | 第一 |
我已经搜索了很多,但我不知道这个选择语句应该是什么样的。 英文:
I have one table Named Table1
| UniqueId | Column B | Column C | Column D | |----------|----------|----------|----------| | 1 | A | Second | abc | | 2 | A | First | def | | 3 | A | Second | ghi |
This Is Table2
| Rank | Value | |------|--------| | 1 | First | | 2 | Second | | 3 | Third |
Now I have to select value like below, condition will be on Column C of Table1 and based on Table2
Like in above table1 column C has three values (Second, First, First), but First in ranked superior then second as per Table2 hence my output should look like before.
Basically I have to select the superior one based on ranking. if Column C Table1 has (Third, Second, Second) so I want to select second, if Column C Table1 has (Third, Second, First) so I want to select First. if all the three value is same then that will be selected.
| UniqueId | Column B | Column C | Column D | Column D | |----------|----------|----------|----------|----------| | 1 | A | Second | abc | First | | 2 | A | First | def | First | | 3 | A | Second | ghi | First |
I have searched a lot but I don't know how that select statement will look like.
答案1 {#1}
得分: 0
你可以在这里使用分析函数first_value:
select t.*,
First_Value(t.c) over(partition by t.b order by r.rank) as NewRank
from t
join ranks r on r.value = t.c
order by UniqueId;
英文:
You could use the analytical function first_value here:
select t.*,
First_Value(t.c) over(partition by t.b order by r.rank) as NewRank
from t
join ranks r on r.value = t.c
order by UniqueId;