I want to display 6369 against ctr_id
2537.
Sample input data:
ctr_id | ctr_id_parent | amount |
---|---|---|
2517 | 2516 | 6369 |
2537 | 2517 | NULL |
I want to display 6369 against ctr_id
2537.
Sample input data:
ctr_id | ctr_id_parent | amount |
---|---|---|
2517 | 2516 | 6369 |
2537 | 2517 | NULL |
Expected result:
ctr_id | ctr_id_parent | amount |
---|---|---|
2517 | 2516 | 6369 |
2537 | 2517 | 6369 |
So basically, when ctr_amount_consumed
is NULL
, then find the ctr_id
equivalent to ctr_id_parent
and display the value of ctr_amount_consumed
of respective ctr_id
.
I tried using fk1 table with different alias's in different joins with combination of ctr_id = ctr_id_parent and also via CTE.
WITH a AS
(
SELECT *
FROM fk1
WHERE ctr_amount_consumed IS NOT NULL
),
b AS
(
SELECT *
FROM fk1
WHERE ctr_amount_consumed IS NOT NULL
)
SELECT
a.ctr_id, b.ctr_id,
a.ctr_id_parent, b.ctr_id_parent,
a.ctr_amount_consumed, b.ctr_amount_consumed
FROM
a
CROSS join
b -- ON a.ctr_id = b.ctr_id_parent
Share
Improve this question
edited Mar 12 at 9:18
marc_s
756k184 gold badges1.4k silver badges1.5k bronze badges
asked Mar 12 at 8:31
Fakhruddin KhambatyFakhruddin Khambaty
31 silver badge2 bronze badges
4
|
2 Answers
Reset to default 3You could try using COALESCE
operator as given below
SELECT
c1.ctr_id,
c1.ctr_id_parent,
COALESCE(c1.amount, c2.amount) AS amount
FROM fk1 c1
LEFT JOIN fk1 c2
ON c1.ctr_id_parent = c2.ctr_id;
A straight-forward sub-query when null should do the trick
select
ctr_id
, ctr_id_parent
, isnull(amount, (select amount from fk1 t2 where t2.ctr.id = t1.ctr_id_parent))
from fk1 t1
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744764389a4592368.html
UNION ALL
for both cases, one query for the rows with amount, one for the others? Something like this? db<>fiddle – Jonas Metzler Commented Mar 12 at 8:41