我有一张看起来像这样的表:
id | name | time | measurement
---+----------+----------------------+----------------
10 | abc | 2015-02-13 20:12:34 | 2
9 | abc | 2015-02-13 19:12:34 | 1
8 | xyz | 2015-02-13 18:12:34 | 1
7 | abc | 2015-02-13 17:12:34 | 0
6 | abc | 2015-02-12 20:12:34 | 0
5 | pqr | 2015-02-12 19:12:34 | 2
4 | pqr | 2015-02-12 18:12:34 | 1
3 | xyz | 2015-02-12 17:12:34 | 0
2 | pqr | 2015-02-12 16:12:34 | 1
1 | abc | 2015-02-12 15:12:34 | 0
我需要每天只选择最后一个条目,最后N天每个名字,其中N是一个常数:
id | name | time | measurement
---+----------+----------------------+----------------
10 | abc | 2015-02-13 20:12:34 | 2
8 | xyz | 2015-02-13 18:12:34 | 1
6 | abc | 2015-02-12 20:12:34 | 0
5 | pqr | 2015-02-12 19:12:34 | 2
3 | xyz | 2015-02-12 17:12:34 | 0
然后计算每天measurement
中每个不同值出现的次数:
day | value | count
------------+-----------+----------
2015-02-13 | 2 | 1
2015-02-13 | 1 | 1
2015-02-12 | 2 | 1
2015-02-12 | 0 | 1
这样做的最佳方式是什么?
答案 0 :(得分:0)
select
to_char(day, 'YYYY-MM-DD') as day,
measurement as value,
count(*) as count
from (
select distinct on (1, name)
date_trunc('day', time) as day, measurement
from t
order by 1, name, time desc
) s
group by 1, 2
order by 1, 2 desc