从表中获取第二高的值

时间:2015-08-24 06:31:18

标签: mysql sql

我有一张这样的表:

+----+---------+------------+
| id | conn_id | read_date  |
+----+---------+------------+
|  1 |       1 | 2010-02-21 |
|  2 |       1 | 2011-02-21 |
|  3 |       2 | 2011-02-21 |
|  4 |       2 | 2013-02-21 |
|  5 |       2 | 2014-02-21 |
+----+---------+------------+

我想要特定'conn_id'的第二高read_date,即我想在conn_id上使用一个组。请帮我解决这个问题。

3 个答案:

答案 0 :(得分:2)

以下是针对特定conn_id的解决方案:

select max (read_date) from my_table
where conn_id=1
and read_date<(
   select max (read_date) from my_table
   where conn_id=1
)

如果您想使用conn_id获取所有group by,请执行以下操作:

select t.conn_id, (select max(i.read_date) from my_table i
where i.conn_id=t.conn_id and i.read_date<max(t.read_date))
from my_table t group by conn_id;

答案 1 :(得分:0)

以下答案应该在MSSQL中起作用:

select id,conn_id,read_date  from (
select *,ROW_NUMBER() over(Partition by conn_id order by read_date desc) as RN 
from my_table
)
where RN =2

这里有一篇关于在MySQL中使用排名函数的有趣文章:
ROW_NUMBER() in MySQL

答案 2 :(得分:0)

如果您的表格设计为ID - 日期匹配(即大ID始终是一个大日期),您可以按ID分组,否则请执行以下操作:

$sql_max = '(select conn_id, max(read_date) max_date from tab group by 1) as tab_max';

$sql_max2 = "(select tab.conn_id,max(tab.read_date) max_date2 from tab, $sql_max
where tab.conn_id = tab_max.conn_id and tab.read_date < tab_max.max_date 
group by 1) as tab_max2";

$sql = "select tab.* from tab, $sql_max2 
where tab.conn_id = tab_max2.conn_id and tab.read_date = tab_max2.max_date2";