简体   繁体   中英

Can SQL Compare rows in same table , and dynamic select value?

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM