按其他列排序后,选择最顶层的非重复条目[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我想为具有重复列值的每一行选择“最顶层”条目。

执行以下查询 -

SELECT *
FROM shop
ORDER BY shop.start_date DESC, shop.created_date DESC;

我得到了结果集 -

+--------+---------+------------+--------------+
| row_id | shop_id | start_date | created_date |
+--------+---------+------------+--------------+
| 1      | 1       | 2017-02-01 | 2017-01-01   |
| 2      | 1       | 2017-01-01 | 2017-02-01   |
| 3      | 2       | 2017-01-01 | 2017-07-01   |
| 4      | 2       | 2017-01-01 | 2017-01-01   |
+--------+---------+------------+--------------+

我可以修改SELECT,以便我只返回每个唯一shop_id的“顶行” - 在这种情况下,row_ids 1和3.可以有1..n个行具有相同的shop_id

同样,如果我上面的查询返回以下顺序,我只想要SELECT row_ids 1和4,因为那些将是每个shop_id的“最顶层”条目。

+--------+---------+------------+--------------+
| row_id | shop_id | start_date | created_date |
+--------+---------+------------+--------------+
| 1      | 1       | 2017-02-01 | 2017-01-01   |
| 2      | 1       | 2017-01-01 | 2017-02-01   |
| 4      | 2       | 2017-01-01 | 2017-07-01   |
| 3      | 2       | 2017-01-01 | 2017-01-01   |
+--------+---------+------------+--------------+
mysql sql
2个回答
0
投票

您可以使用子查询来执行此操作:

select s.* 
from shop s 
where s.row_id = (
  select row_id 
  from shop 
  where shop_id = s.shop_id 
  order by start_date desc, created_date desc 
  limit 1
)   

请注意在此查询示例中row_id对于每个shop_id的uniq的假设。

Demonstration

或者像这样:

select t.*
from shop t
join (
 select t2.shop_id, t2.start_date, max(t2.created_date) as created_date 
 from shop t2
 join (
   select max(start_date) as start_date, shop_id
   from shop
   group by shop_id
 ) t3 on t3.shop_id = t2.shop_id and t3.start_date = t2.start_date
 group by t2.shop_id, t2.start_date
) t1 on t1.shop_id = t.shop_id and t.start_date = t1.start_date and t.created_date = t1.created_date

请注意,如果有相同start_date的相同created_dateshop_id的记录,你需要在外部查询中使用另一个group by s.shop_id, s.start_date, s.created_date(将min(row_id)添加到group by中的select中列出的其他列)

Demonstration


0
投票

尝试加入子查询,查找每个shop_id的“顶部”行:

SELECT t1.*
FROM shop t1
INNER JOIN
(
    SELECT shop_id, MIN(row_id) AS min_id
    FROM shop
    GROUP BY shop_id
) t2
    ON t1.shop_id = t2.shop_id AND
       t1.row_id = t2.min_id
ORDER BY
    t1.start_date DESC,
    t1.created_date DESC;

enter image description here

Demo

© www.soinside.com 2019 - 2024. All rights reserved.