由另一个子 table 订购 table
Ordering a table by another sub-table
我有两个通过一对多关系连接的 table(table A 中的一条记录将在 Table B 中有多个连接到它)。作为参考,Table A 持有事件记录,而 Table B 持有为 Table A 中事件的进展添加的注释。
Tables:
Table答:
SELECT [IncID]
,[TechId]
,[TechName]
,[Complete]
,[StartDateTime]
,[CompleteDateTime]
,[Subject]
,[Description]
,[Resolution]
FROM [TableA]
Table乙:
SELECT TOP 1000 [IncHistID]
,[IncID]
,[TechID]
,[TechName]
,[NoteDate]
,[NoteTime]
,[Description]
,[ContactName]
,[RowNum]
FROM [TableB]
两个 table 通过 [IncID] 列连接。我希望能够通过 TableB 的 NoteDate 列来订购 TableA。
我使用以下查询按所需顺序获得了 TableB:
SELECT [IncID]
,Max(Notedate) as NoteDate
FROM [PDSupport].[dbo].[vwWebIncidentsHist3]
Group by IncID
Order By Notedate Desc
假设您在两个表中都有关于 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
我有两个通过一对多关系连接的 table(table A 中的一条记录将在 Table B 中有多个连接到它)。作为参考,Table A 持有事件记录,而 Table B 持有为 Table A 中事件的进展添加的注释。
Tables:
Table答:
SELECT [IncID]
,[TechId]
,[TechName]
,[Complete]
,[StartDateTime]
,[CompleteDateTime]
,[Subject]
,[Description]
,[Resolution]
FROM [TableA]
Table乙:
SELECT TOP 1000 [IncHistID]
,[IncID]
,[TechID]
,[TechName]
,[NoteDate]
,[NoteTime]
,[Description]
,[ContactName]
,[RowNum]
FROM [TableB]
两个 table 通过 [IncID] 列连接。我希望能够通过 TableB 的 NoteDate 列来订购 TableA。
我使用以下查询按所需顺序获得了 TableB:
SELECT [IncID]
,Max(Notedate) as NoteDate
FROM [PDSupport].[dbo].[vwWebIncidentsHist3]
Group by IncID
Order By Notedate Desc
假设您在两个表中都有关于 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