此查询有什么问题,请告诉我。 从内部查询我想根据EventID选择前1组。
请建议做什么。
SELECT TOP 1 * FROM
(
SELECT E.EventID, ETD.EventName, ED.EventDate FROM
[3rdi_EventDates] AS ED inner join [3rdi_Events] as E on ED.EventID=E.EventID
inner join [3rdi_EventTypeDetails] as ETD on E.EventTypeId=ETD.EventTypeId
WHERE E.EventID in
(
select EventId from [3rdi_Events] WHERE
EventID IN (select distinct EventId from [3rdi_EventDates] where EventDate Between '2/9/2011' and '3/11/2012')
) ORDER BY ETD.EventName, ED.EventDate
) AS temp Group by EventID
答案 0 :(得分:1)
您希望每个EventID有一条记录,在这种情况下,请使用Row_Number()和分区。
您的两个子查询级别也不需要,内部联接涉及子查询中的两个表,因此您可以直接在主查询中进行过滤。
要做的最后一点是日期文字最好使用YYYYMMDD编写,以便对任何区域或日期格式设置都是健壮的。
SELECT EventID, EventName, EventDate
FROM (
SELECT E.EventID, ETD.EventName, ED.EventDate,
ROW_NUMBER() over (
partition by E.EventID
ORDER BY ETD.EventName, ED.EventDate) RowNum
FROM [3rdi_EventDates] AS ED
inner join [3rdi_Events] as E on ED.EventID=E.EventID
inner join [3rdi_EventTypeDetails] as ETD on E.EventTypeId=ETD.EventTypeId
where ED.EventDate Between '20110209' and '20120311'
) AS temp
WHERE RowNum = 1
答案 1 :(得分:0)
使用此功能。
SELECT TOP 1 * FROM (
SELECT E.EventID, ETD.EventName, ED.EventDate FROM
[3rdi_EventDates] AS ED inner join [3rdi_Events] as E on ED.EventID=E.EventID
inner join [3rdi_EventTypeDetails] as ETD on E.EventTypeId=ETD.EventTypeId
WHERE ED.EventDate > Convert(Datetime,'2/9/2011') and ED.EventDate < Convert(Datetime,'3/11/2012')
ORDER BY ETD.EventName, ED.EventDate)