我还有一个问题,但这有点令人困惑,所以这次我将尝试简化。
我有一个表“ option”:
id | option_name
1 "Option 1"
2 "Option 2"
3 "Option 3"
4 "Option 4"
5 "Option 5"
6 "Option 6"
7 "Option 7"
和另一个表“ user”,其中包含一些用户信息。然后,我创建了一个名为“ daily_voting”的表,每个用户每天都可以选择一个选项。应该是这样的:
user_id | option_id | timestamp
1 1 2018-12-24 00:01:00.091055-03
2 1 2018-12-24 01:01:00.091055-03
3 2 2018-12-24 02:01:00.091055-03
1 2 2018-12-25 00:01:00.091055-03
2 2 2018-12-25 00:02:00.091055-03
3 5 2018-12-26 00:02:00.091055-03
如果我这样做:
select count(*) as votes, option_id, date_trunc('day', daily_voting.timestamp) as day
from daily_voting
where date_trunc('day', daily_voting.timestamp) = '2018-12-24 00:00:00-03'
group by option_id, day
order by votes desc
limit 1
我会得到:
votes | option_id | day
2 1 2018-12-24 00:00:00-03
我需要的是,从当前日期过去一周,可能是:
date_trunc('week', current_date) and date_trunc('week', current_date+7)
查询的输出将是:
votes | option_id | day
2 1 2018-12-24 00:00:00-03
2 2 2018-12-25 00:00:00-03
1 5 2018-12-26 00:00:00-03
答案 0 :(得分:0)
ROW_NUMBER()
将为您排名。
SELECT Votes, Option_ID, Day
FROM (
SELECT Votes, Option_id, day, row_number() over (partition by day order by votes DESC) AS VoteRank
FROM (
select count(*) as votes, option_id, date_trunc('day', daily_voting.timestamp) as day
from daily_voting
where date_trunc('day', daily_voting.timestamp) BETWEEN '2018-12-24' AND '2018-12-31'
group by option_id, day
)Aux ) T
WHERE VoteRank = 1
您可以随意使用其他方法定义日期范围。