2012-07-27 195 views
0

我有這個查詢獲取三個不同表的最大日期記錄。我可以在這些桌子上做一個工會,讓他們全部返回他們各自的日期。但是,我無法找到一種方法來選擇返回的這三條記錄的最大值。有任何想法嗎?從三個不同的選擇最大查詢中選擇最大值

SELECT MAX (Date_submitted) as a 
FROM [AngelSQL] . [dbo]. [LSN_RESPONSES] , ACCOUNTS , LSN_ENTRIES , GB3_ASSOCIATIONS 
where 
LSN_RESPONSES . USER_ID = accounts . username 
and LoginName = 'admin' 
and TakenFromCourseId = 'TT-TC-TS-TD-Test-Test' 
and LSN_RESPONSES . PARENT_ID = LSN_ENTRIES .ENTRY_ID 
and LSN_RESPONSES . PARENT_ID = GB3_ASSOCIATIONS .LSN_ENTRY_ID 
union 
SELECT MAX (dateEnd) as a 
FROM [AngelSQL] . [dbo]. [qti_assessment_attempt] ,dbo . ACCOUNTS, COURSES, qti_question_containers, GB3_ASSOCIATIONS 
where accounts . PERSON_ID = qti_assessment_attempt .person_id 
and 
taken_from_course_container_id = courses. CONTAINER_ID 
and 
accounts .LoginName = 'admin' 
and COURSES . COURSE_ID= 'TT-TC-TS-TD-Test-Test' 
and qti_assessment_attempt . question_container_id = qti_question_containers. id 
and qti_question_containers . entry_ID = GB3_ASSOCIATIONS .LSN_ENTRY_ID 
union 
SELECT MAX (PostDate) as a 
FROM dbo . ACCOUNTS, DiscussionPost , DiscussionForum , GB3_ASSOCIATIONS 
where 
accounts .USERNAME = DiscussionPost. AuthorId 
and 
LoginName ='admin' 
and 
discussionpost . CourseContext = 'TT-TC-TS-TD-Test-Test' 
and 
DiscussionPost . ForumId = DiscussionForum .ForumId 
and DiscussionForum . EntryId = GB3_ASSOCIATIONS .LSN_ENTRY_ID} 

回答

1

使用您的查詢作爲子查詢/ CTE,像這樣:

with t as (<put your query here>) 
select max(a) 
from t 
+0

偉大的工作完美。 – Matt 2012-07-30 17:23:04