简体   繁体   中英

How to Select master table data and select referance table top one data sql query

i need an sql query which should return the master table entry and its child table entry ( the latest one entry only ). I used inner join for this. But i its not working fine. Can anyone give a give me a proper query for this

Thanks in advance

In SQLServer2005+ use option with OUTER APPLY operator

SELECT *
FROM master t1 OUTER APPLY (
                            SELECT TOP 1 t2.Col1, t2.Col2 ...
                            FROM child t2
                            WHERE t1.Id = t2.Id
                            ORDER BY t2.CreatedDate DESC
                            ) o

OR option with CTE and ROW_NUMBER() ranking function

;WITH cte AS
 (                            
  SELECT *, 
         ROW_NUMBER() OVER(PARTITION BY t1.Id ORDER BY t2.CreatedDate DESC) AS rn
  FROM master t1 JOIN child t2 ON t1.Id = t2.Id
  )
  SELECT *
  FROM cte
  WHERE rn = 1

Try this,

SELECT ID, DATE
(
SELECT M.ID, C.DATE, ROW_NUMBER() OVER(PARTITION BY M.ID ORDER BY C.DATE DESC) RN
FROM MASTER M
JOIN CHILD C
ON C.ID = M.ID
) A
WHERE RN = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM