Although I know this isn't very efficient, I need to get this working fast so I try to follow the easiest path, or at least I thought so. I'm trying to get the max data out of an entity and take into consideration only the rows where USER is not null, and in case no rows have USER not set to null, then I will take the null ones into consideration.
The entity's structure is as follows:
- Id int,
- ParentId int,
- Guid varchar,
- EventOn DateTime,
- User int (null)
So, the query is the following one:
select RS.[$Id] RangeSheet,
GRST.EventOn,
RSIS.Id [Status],
RSIS.Name StatusRefex
from RangeSheet RS
left outer join (select RST.ParentId RangeSheet,
MAX(RST.EventOn) EventOn
from RangeSheetTime RST
where RST.[User] is (case RST.[User] when null then null else not null)
group by RST.ParentId) GRST on RS.[$Id]=GRST.RangeSheet
left outer join RangeSheetTime RST on GRST.EventOn=RST.EventOn
and GRST.RangeSheet=RST.ParentId
left outer join RangeSheetItemState RSIS on (case when RST.StartOrEnd = 1 then 1 when RST.StartOrEnd = 0 then 4 else null end) = RSIS.Id
where RS.[$IsDeleted]=0
The case I'm having trouble with is the one inside the view GRST. What could I do to accomplish my requirements?