I have a Sql Server 2005 table with following data:
idHearing is the primary key (identity), idCase is a foreign key that may duplicate. StartDate and StartTime specify the date and time of the event - both fields are of DateTime type (for whatever reason these are separate fields). All StartDate data has a time of 12:00:00. All StartTime data has a date of 1/1/1900. IsScheduled and IsOnCalendar are bit fields.
My challenge is to select the latest (in terms of Date/Time) hearing for each idCase. If the StartDate/StartTime are identical (as is in the rows 1 and 2), preference should be given to a row which has IsScheduled and/or IsCalendar on. If those are columns are same as well, then it does not matter which row gets returned.
To make this more complicated, I must do it all in single SELECT statement (because it must be in a view) and I have to return all the columns that you see below.
I've tried several ways, but my SQL-FU isn't strong. Any ideas?