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

时间:2017-12-21 01:47:51

标签: mysql sql

我想选择最顶级的"具有重复列值的每一行的条目。

执行以下查询 -

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_id s 1和3.可以有 1..n 具有相同shop_id的行数。

同样,如果我上面的查询返回了以下顺序,我只想SELECT row_id s 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   |
+--------+---------+------------+--------------+

2 个答案:

答案 0 :(得分: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的{​​{1}} created_date相同的记录,您需要使用另一个shop_id在外部查询中(将group by s.shop_id, s.start_date, s.created_date添加到min(row_id)group by中列出的其他列

Demonstration

答案 1 :(得分:0)

尝试加入子查询,找到" top"每个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