使用具有两列以上的聚合函数

时间:2009-10-08 16:12:03

标签: sql postgresql aggregate

我有两个表,stats和stat_log。统计日志是这样的:

user_id,stat_id,value,registered

并记录给定时间的统计值。我需要给定用户的每个统计数据的最后一个值。

所以我想要这样的东西,但有价值观: select stat,max(registered) from stat_log where uid = 1 group by stat;

 stat |    max       
------+------------  
    6 | 2009-10-08  
    1 | 2009-10-08  
    3 | 2009-10-08  
    5 | 2009-10-08  
    7 | 2009-10-08  
    4 | 2009-10-08  

相反,我有这个:

select stat,max(registered),value from stat_log where uid = 1 group by stat,value;

 stat |    max     | value   
------+------------+-------  
    4 | 2009-10-08 | 38  
    5 | 2009-10-08 | 118  
    1 | 2009-10-08 | 100  
    1 | 2009-10-07 | 101  
    6 | 2009-10-08 | 68  
    3 | 2009-10-08 | 110    
    7 | 2009-10-08 | 53

什么是正确的查询?这是PostgreSQL 8.3。

3 个答案:

答案 0 :(得分:3)

select
    distinct on (stat_id)
    *
FROM
    stat_log
WHERE
    user_id = 1
order by stat_id desc, registered_desc;

答案 1 :(得分:0)

不确定这是否是PostgreSQL的有效SQL,但我认为你应该能够使用这样的东西:

select * from stat_log
inner join (
    select uid,stat,max(registered) as registered from stat_log group by uid,stat
) as maxrecords on stat_log.stat = maxrecords.stat and
                   stat_log.uid = maxrecords.uid and
                   stat_log.registered = maxrecords.registered
where stat_log.uid = 1

'内部联接'将结果限制为内部子查询返回的您感兴趣的行。

答案 2 :(得分:0)

我在Oracle中使用了一些非标准功能,但是否则需要子查询或连接。我喜欢这种形式,因为它对我来说是合乎逻辑的,但理想情况下,数据库会以与加入版本相同的方式执行它。

select stat, registered, value
from stat_log a
where
    id = 1
    and registered = (
        select max(registered)
        from stat_log
        where
            b.id = a.id
            and b.stat = a.stat
        )