如何只获得每天的第一个记录?

时间:2018-05-23 19:08:41

标签: sql greatest-n-per-group

如何只获取每天的第一批记录?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="slider-range">
</div>

我想收到:

id | name | date
1  | aaa  | 2018-05-10
2  | bbb  | 2018-05-10
3  | ccc  | 2018-05-10
4  | ddd  | 2018-05-11
5  | eee  | 2018-05-11
6  | fff  | 2018-05-13

3 个答案:

答案 0 :(得分:1)

对于Postgres,有一个更有效的解决方案:

select distinct on (id) id, name, date
from the_table
order by id, date;

答案 1 :(得分:0)

CREATE TABLE T1
    (id int, name varchar2(3), dat timestamp)
;

INSERT ALL 
    INTO T1 (id, name, dat)
         VALUES (1, 'aaa', '10-May-2018 12:00:00 AM')
    INTO T1 (id, name, dat)
         VALUES (2, 'bbb', '10-May-2018 12:00:00 AM')
    INTO T1 (id, name, dat)
         VALUES (3, 'ccc', '10-May-2018 12:00:00 AM')
    INTO T1 (id, name, dat)
         VALUES (4, 'ddd', '11-May-2018 12:00:00 AM')
    INTO T1 (id, name, dat)
         VALUES (5, 'eee', '11-May-2018 12:00:00 AM')
    INTO T1 (id, name, dat)
         VALUES (6, 'fff', '13-May-2018 12:00:00 AM')
SELECT * FROM dual
;
  

查询 -

select id, name, dat from (
select id, name, dat, dense_rank() over (partition by dat order by id) as rnk
from t1
  ) where rnk = 1;



ID  NAME    DAT
1   aaa 2018-05-10 00:00:00.0
4   ddd 2018-05-11 00:00:00.0
6   fff 2018-05-13 00:00:00.0

答案 2 :(得分:0)

如果ID是Pk,则此查询可以在PostgreSQL和MySql上运行

编写子查询以在表中按MIN获取date id,然后自行加入

SELECT t1.*
FROM (
  SELECT MIN(ID) minId
  FROM T1 
  GROUP BY date
) t inner join t1 on t.minid = t1.id

sqlfiddle:http://sqlfiddle.com/#!9/9a48d7/4