3

我需要一个 sql 查询,它应该返回主表条目及其子表条目(仅最新的一个条目)。我为此使用了内部连接。但我它不能正常工作。谁能给我一个适当的查询

提前致谢

4

2 回答 2

1

在 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

具有CTEROW_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
于 2013-04-04T11:24:56.993 回答
0

试试这个,

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
于 2013-04-04T11:30:59.597 回答