我有两个表通过一对多关系连接(表A中的一个记录将在表B中有多个连接到它的记录)。作为参考,表A保留了事件记录,而表B保存了表A中事件进展的附注。
表格:
表A:
SELECT [IncID]
,[TechId]
,[TechName]
,[Complete]
,[StartDateTime]
,[CompleteDateTime]
,[Subject]
,[Description]
,[Resolution]
FROM [TableA]
表B:
SELECT TOP 1000 [IncHistID]
,[IncID]
,[TechID]
,[TechName]
,[NoteDate]
,[NoteTime]
,[Description]
,[ContactName]
,[RowNum]
FROM [TableB]
两个表通过[IncID]列连接。我希望能够通过TableB的NoteDate Column订购TableA。
我使用以下查询以所需顺序获得了TableB:
SELECT [IncID]
,Max(Notedate) as NoteDate
FROM [PDSupport].[dbo].[vwWebIncidentsHist3]
Group by IncID
Order By Notedate Desc
答案 0 :(得分:1)
假设您在两个表中都有IncID索引,使用连接然后简单排序似乎是最有效和最标准的方法......
SELECT A.[IncID]
,A.[TechId]
,A.[TechName]
,A.[Complete]
,A.[StartDateTime]
,A.[CompleteDateTime]
,A.[Subject]
,A.[Description]
,A.[Resolution]
,max(B.noteDate) mNotedate
FROM tableA A
LEFT JOIN tableB B
on A.IncID=B.IncID
GROUP BY A.[IncID]
,A.[TechId]
,A.[TechName]
,A.[Complete]
,A.[StartDateTime]
,A.[CompleteDateTime]
,A.[Subject]
,A.[Description]
,A.[Resolution]
ORDER BY mNoteDate desc