[英]select the rows based on unique column of each group from the table
---------------- c_id s_id p_id (customer_id, service_id, provider_id) ---- ---- ------ 1, 1, 1 - not elegible to select as next entry has same p_id 1, 2, 1 1, 3, 3 2, 1, 1 2, 2, 2 2, 3, 3 3, 1, 3 - not elegible to select as next entry has same p_id 3, 2, 3 - not elegible to select as next entry has same p_id 3, 3, 3
What is the cost effective way of writing the query to produce below result from above data ?编写查询以从上述数据生成以下结果的成本有效的方法是什么?
---------------- c_id s_id p_id ---- ---- ------ 1, 2, 1 1, 3, 3 2, 1, 1 2, 2, 2 2, 3, 3 3, 3, 3
In MySQL 8.0, you can use lead()
to retrieve the "next" p_id
, and use that information to filter out rows whose pid
is the same as the next value.在 MySQL 8.0 中,您可以使用lead()
检索“下一个” p_id
,并使用该信息过滤掉pid
与下一个值相同的行。
select *
from (
select t.*, lead(p_id) over(partition by c_id order by s_id) lead_p_id
from mytable t
) t
where not p_id <=> lead_p_id
In earlier versions, you would typically use a correlated subquery:在早期版本中,您通常会使用相关子查询:
select t.*
from mytable t
where not pid <=> (
select p_id
from mytable t1
where t1.c_id = t.c_id and t1.s_id > t.s_id
order by t1.s_id
limit 1
)
I'm not too sure if this is the most cost effective, but it def seems to be the most obvious solution I could think of.我不太确定这是否最具成本效益,但它似乎是我能想到的最明显的解决方案。
select
c_id
,max(s_id) [s_id]
,p_id
from
`table_name`
group by
c_id
,p_id
If s_id
is a sequence with no gaps, you can use:如果s_id
是一个没有间隙的序列,您可以使用:
select t.*
from t left join
t tnext
on tnext.c_id = t.c_id and tnext.s_id = t.sid + 1
where not (tnext.p_id <=> t.p_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.