UPDATE complete rewrite after question updated with more data (see edit history if really interested in my prior ramblings).
Assumptions/Understandings:
A.Val
is unique (eg, there is only one row where A.Val = 423
) otherwise we'll need more info for the join from B
to A
(eg, if 3x rows have A.Val = 423
do we return 3 rows/A.text
values, or do we limit the match to a single row via additional criteria?)
- if no match in table
A
then return A.text = NULL
(hence the left join
)
Where I need more input from OP is on the B->A
join. From OP's comment we know that for Label = 'Adria'
we want to pull the row from A
where Val = max(Val) = 568
, but what I'm not sure about is if I can apply the max()
to B.Val
or do I need to apply the max()
to A.Val
:
- limit the
B->A
join to A.Val = max(B.Val)
or ...
- limit the
B->A
join to A.Val = max(A.Val)
One idea for limit the B->A
join to A.Val = max(B.Val)
select CB.Label, A.text
from (select C.Label, max(B.Val) as maxVal
from C
join B
on C.Label = B.Label
and C.Label = 'Adria'
group by C.Label) as CB
left
join A
on A.Val = CB.maxVal
go
Label text
---------- ----------
Adria bars
If we delete A where Val = 568
(so that A.Val = max(B.Val) = 568
fails) the query returns:
Label text
---------- ----------
Adria NULL
One idea for limit the B->A
join to A.Val = max(A.Val)
select dt.Label, A.text
from (select C.Label, max(A.Val) as maxVal
from C
join B
on C.Label = B.Label
and C.Label = 'Adria'
left
join A
on A.Val = B.Val
group by C.Label) as dt
left
join A
on A.Val = dt.maxVal
go
Label text
---------- ----------
Adria bars
If we delete A where Val = 568
(so that A.Val = dt.maxVal = 423
) the query returns:
Label text
---------- ----------
Adria tuh
If we delete A
(so that A.Val = dt.maxVal
fails) the query returns:
Label text
---------- ----------
Adria NULL
NOTE: Above queries (barring any cut-n-paste typos on my behalf) were run on ASE 15.7 SP140
.