带有时间间隔的SQL查询

时间:2014-10-01 20:41:12

标签: sql postgresql relational-database

我想在“2014-07-01”和“2014-08-01”之间获得最佳3天用户

有人可以帮助我吗?我已经被困在这里3天了。

在真实分数表中,条目是10:00到22:00,每小时1个条目。

每天和每位玩家共有12个条目(有时可能少于1或2)。

这是我想要获得的输出:

ID | User_ID | Username | Sum(Score) | Date
--------------------------------------------------
 1  |    1   |   Xxx    |     52     | 2014-07-01
 2  |    1   |   Xxx    |     143    | 2014-07-02
 3  |    2   |   Yyy    |     63     | 2014-07-01
...

Score表:

ID | User_ID | Score | Datetime
-----------------------------------------
 1 |    1    | 35   | 2014-07-01 11:00:00
 2 |    1    | 17   | 2014-07-01 12:00:00
 3 |    2    | 36   | 2014-07-01 11:00:00
 4 |    2    | 27   | 2014-07-01 12:00:00
 5 |    1    | 66   | 2014-07-02 11:00:00
 6 |    1    | 77   | 2014-07-02 12:00:00
 7 |    2    | 93   | 2014-07-02 12:00:00
 ...

User表:

ID | Username
--------------
1  |  Xxx
2  |  Yyy
3  |  Zzz
...

2 个答案:

答案 0 :(得分:1)

我认为您需要先按日期汇总,然后使用row_number()选择前三个。要进行聚合:

select s.user_id, sum(s.datetime, 'day') as theday, sum(score) as score,
       row_number() over (partition by s.user_id order by sum(score) desc) as seqnum
from scores s
group by s.user_id;

要获取其余信息,请将其用作子查询或CTE:

select u.*, s.score
from (select s.user_id, sum(s.datetime, 'day') as theday, sum(s.score) as score,
             row_number() over (partition by s.user_id order by sum(s.score) desc) as seqnum
      from scores s
      group by s.user_id
     ) s join
     users u
     on s.user_id = u.users_id
where seqnum <= 3
order by u.user_id, s.score desc;

答案 1 :(得分:1)

SELECT      'group has no id'   as ID,
            u.ID                as User_ID,
            u.Username,
            sum(s.Score)        "Sum(Score)",
            s.Datetime::date    as Date
FROM        User u,
            Score s
WHERE       u.id = s.User_ID
AND         s.Datetime BETWEEN '2014-07-01' AND '2014-08-01 23:59:59'
GROUP BY    u.ID, u.Username, s.Datetime::date
ORDER BY    sum(s.Score) DESC
LIMIT 3;