如何只获得每天的第一个记录?
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
我想收到:
1 | aaa | 2018-05-10
4 | ddd | 2018-05-11
6 | fff | 2018-05-13
如果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
对于Postgres,有一个更有效的解决方案:
select distinct on (id) id, name, date
from the_table
order by id, date;
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