[英]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 ). 我需要一个sql查询,它应该返回主表项和它的子表项( 仅最新的一个条目 )。 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 在SQLServer2005中使用选项和OUTER APPLY运算符
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 带有CTE和ROW_NUMBER()排名功能的OR选项
;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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.