Hope you're doing well
I have a table with the structure below :
Customer_Channel_Branch:(Customer_Num int ,Channel_Num int ,Branch_Code int ,Issue_date datetime)
Some Example Data :
"Customer_Channel_Branch"
---------------------------------------------------------
Customer_Num Channel_Num Branch_Code Issue_date
x 1 1000 1990
x 2 2000 1991
x 3 3000 2000
There is another table with this structure below:
Channel_general_Code:(Channel_Num int , Channel_gnrl_Code int)
some example data for this table:
"Channel_general_Code"
-------------------------------------------
Channel_Num Channel_gnrl_Code
1 1
2 1
3 1
As you can see in the second table , all three Channel_Num --> (1,2,3)
are grouped as one single channel . So what I want in the result set is this :
"result"
----------------------------------------------
Customer_Num Channel_Num Branch_Code
x 1 1000
x 2 1000
x 3 1000
for Channel_Num
s that are considered as one , (have the same Channel_gnrl_Code
in the second table), I need the Branch_Code
of the Channel_Num
with lowest Issue_date
.
I thought that I could use window functions
(`row_number() over(partition by Channel_gnrl_Code order by Issue_date )`)
to write this query but it gave me a false result.
I was wondering if you could help me with this.
Thanks in advance
Best Answer
Avoid
Row_Number
because first it process whole table then again you select row where rn=1 for each group