SQL 可以比较相同 table 和动态 select 值中的行吗?
Can SQL Compare rows in same table , and dynamic select value?
最近,我得到了一个 table 的名字 Appointments
要求是我需要 select 每个客户只有一行,符合 2 条规则:
如果同一时间和(同一地点或不同地点),请将导师和地点设为空。
如果不同时间和(相同位置或不同位置),选择最小的行。
由于我在SQL方面太业余了,我搜索了自连接的方法,但在这种情况下似乎不起作用。
预期结果
谢谢大家,祝你有美好的一天...
您似乎想要每个客户的最短时间,如果有多行且导师或位置不匹配,则使用 null
值。
您可以使用 window 函数:
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
最近,我得到了一个 table 的名字 Appointments
要求是我需要 select 每个客户只有一行,符合 2 条规则:
如果同一时间和(同一地点或不同地点),请将导师和地点设为空。
如果不同时间和(相同位置或不同位置),选择最小的行。
由于我在SQL方面太业余了,我搜索了自连接的方法,但在这种情况下似乎不起作用。
预期结果
谢谢大家,祝你有美好的一天...
您似乎想要每个客户的最短时间,如果有多行且导师或位置不匹配,则使用 null
值。
您可以使用 window 函数:
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