我有以下SQL表:
[日历]
[CalendarId]
[Name]
样本数据:
CalendarId ResourceKey Name
1 1 tk1-Room1
2 2 tk1-Room2
3 3 tk1-noentries
[CalendarEntry]
[CalendarId]
[CalendarEntryId]
[Start]
[End]
样本数据:
CalendarId Start End
1 2019-11-18 16:00:00.0000000 2019-11-18 17:00:00.0000000
1 2019-11-19 16:00:00.0000000 2019-11-19 17:00:00.0000000
2 2019-11-25 16:00:00.0000000 2019-11-25 17:00:00.0000000
1 2019-11-25 17:00:00.0000000 2019-11-25 18:00:00.0000000
预期输出:
Name StartDate EndDate ResourceKey
tk1-Room1 2019-11-25 17:00:00 2019-11-25 17:00:00 1
tk1-Room2 2019-11-25 16:00:00 2019-11-25 17:00:00 2
tk1-noentries NULL NULL 3
我正在尝试列出所有Calendar
条目,以及它们对应的开始(最近)和结束时间。
我有以下代码可以部分工作:
SELECT Name,StartDate,ResourceKey FROM [Calendar].[dbo].[Calendar] CAL
LEFT JOIN(
SELECT
CalendarId,MAX(ENT.[Start]) as StartDate
FROM [CalendarEntry] ENT
GROUP BY CalendarId
)
AS ST on CAL.CalendarId = ST.CalendarId
但是,如果我要包括该列,请在我的子SELECT中,例如EG:
SELECT
CalendarId,MAX(ENT.[Start]) as StartDate,ENT.[End] as endDate
我收到以下错误:
Column 'CalendarEntry.End' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
但是,现在将其包含在GROUP BY中会导致每个日历返回多个CalendarEntry行。
对我来说,从CalendarEntry中获取最新行以允许我访问所有列的最佳方法是什么?
谢谢!