Recently, i got a table which name Appointments
The requirement is that i need to select only one row for each customer by 2 rule:
if same time and (same location or different location), put null on tutor and location.
if different time and (same location or different location), pick the smallest row.
Since i’m so amateur in SQL, i’ve search the method of self join, but it seems not working in this case.
Expected result
Thanks all, have a great day…
Advertisement
Answer
You seem to want the minimum time for each customer, with null
values if there are multiple rows and the tutor or location don’t match.
You can use window functions:
select customer, starttime, (case when min(location) = max(location) then min(location) end) as location, (case when min(tutor) = max(tutor) then min(tutor) end) as tutor from (select t.*, rank() over (partition by customer order by starttime) as seqnum from t ) t where seqnum = 1 group by customer, starttime