두 개의 테이블, stat 및 stat_log가 있습니다. 스탯 로그는 다음과 같이이다 :두 개 이상의 열이있는 집계 함수 사용
user_id,stat_id,value,registered
을하고는 주어진 시간에 대한 통계의 값을 기록합니다. 주어진 사용자에 대한 모든 통계의 모든 마지막 값이 필요합니다.
그래서 나는이 같은 것을 원하지만, 값 :
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
정확한 쿼리 기능 : 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
대신 나는이있어? 이것은 PostgreSQL 8.3입니다.
은 '내부 조인'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
당신이 관심있는 행에 결과를 제한이 PostgreSQL의 유효한 SQL이지만, 난 당신이 이런 일을 사용할 수 있어야한다고 생각합니다 여부를
유효하지만 다른 사용자, 두 날짜 등 모두를 반환합니다. –
whoops. 어떻게 든 통계가 기본 키라고 생각했습니다. "distinct on"(내가 위의 허용 된 대답을 볼 때까지 존재하지 않았던 것)이라는 편집을 수정하고 수정했습니다. 훨씬 더 나은 해결책 인 것 같습니다. – iammichael