Click here to Skip to main content
15,889,595 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two tables like DataHeader and DataDetail
i want to display the Remarks from DataDetail table which are having high DDid
and if remarks not available in DataDetail then I want to display Remarks from DataHeader Table

how to write query in SQL

DataHeader
DHid A B C Remarks
1 abc 123 xyz DHidR1
2 bcd 252 jhyvb DHidR2
3 efg 541 sdh DHidR3

DataDetail
DHid DDid Remarks
1 1 working
1 2 working
1 3 worked
2 1 Remarks1
2 2 Remarks2
2 3 Remarks3
2 4 Remarks4
2 5 Remarks5

i want to display the data like
DHid A B C Remarks
1 abc 123 xyz worked
2 bcd 252 jhyvb Remarks5
3 efg 541 sdh DHidR3



Sry I Cant write tables format

What I have tried:

i have tried left outer join to Dataheader and i displaying dataheader remarks only
Posted
Updated 20-Mar-18 4:53am

1 solution

Something like this:
SQL
SELECT
    DH.DHid,
    DH.A,
    DH.B,
    DH.C,
    IsNull(
        (
            SELECT TOP 1 DD.Remarks
            FROM DataDetail As DD
            WHERE DD.DHid = DH.DHid
            And DD.Remarks Is Not Null
            ORDER BY DD.DDid DESC
        ),
        DH.Remarks
    ) As Remarks
FROM
    DataHeader As DH
;

Or:
SQL
WITH cteDetail As
(
    SELECT
        ROW_NUMBER() OVER (PARTITION BY DHid ORDER BY DDid DESC) As RN,
        DHid,
        Remarks
    FROM
        DataDetail
    WHERE
        Remarks Is Not Null
)
SELECT
    DH.DHid,
    DH.A,
    DH.B,
    DH.C,
    IsNull(DD.Remarks, DH.Remarks) As Remarks
FROM
    DataHeader As DH
    LEFT JOIN cteDetail As DD
    ON DD.DHid = DH.DHid
    And DD.RN = 1
;
 
Share this answer
 
Comments
Maciej Los 20-Mar-18 15:08pm    
Oh, no! Another 5!
:laugh:
Parazival 26-Mar-18 10:36am    
its showing only DataDetail Remarks(high value of remarks) only if all are empty from Datadetail its not fetching Remarks from DataHeader table .
I have tried First solution
thanks for replay Richard
Richard Deeming 26-Mar-18 13:59pm    
Given the sample data you have provided, both queries produce the exact output you requested.

Demo[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900