最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sql server - Get value from first row to another based on different primary key values - Stack Overflow

programmeradmin2浏览0评论

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
  • Please tag your RDBMS - SQL Server I assume? – Dale K Commented Mar 12 at 8:37
  • Do you want 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
  • You've probably just noticed that you can't accept both answers... so choose the one your prefer (they are both roughly equivalent). – Dale K Commented Mar 12 at 8:48
  • what if also amount of id 2517 is NULL? You have to look for his parent too? maybe you need a recursive cte – MtwStark Commented Mar 12 at 13:43
Add a comment  | 

2 Answers 2

Reset to default 3

You 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
发布评论

评论列表(0)

  1. 暂无评论