SQL子查询和分组

时间:2012-08-29 23:06:10

标签: sql postgresql

我应该能做到这一点,但大脑似乎已经融化了

数据库是postgres

表结构很简单,只有四列重要:

位置,用户,活动,日期时间

我需要按位置排序并输出已发生的每个活动的最新事件。我事先不知道活动是什么

这样的东西
Location    User    Activity   DateTime
London      Fred    A          08-29-2012
London      Fred    B          08-27-2012
Paris       John    A          08-29-2012
Tokyo       Fred    A          08-17-2012
Tokyo       Jane    D          08-29-2012

谢谢民众

4 个答案:

答案 0 :(得分:4)

PostgreSQL中最快的方式可能是DISTINCT ON

SELECT DISTINCT ON (location, activity)
       location, activity, datetime, usr
FROM   tbl
ORDER  BY location, activity, datetime DESC, usr; -- usr only to break ties

带有位置参数的简表:

SELECT DISTINCT ON (1 ,2)
       location, activity, datetime, usr
FROM   tbl
ORDER  BY 1, 2, 3 DESC, 4;

这在一次操作中将排序和缩减组合成不同的行。 this related answer中的更多细节,解释和基准。

user是保留字。实际上不要将它用作列名。我用usr代替。

如果表现至关重要,则以下指数会产生影响:

CREATE INDEX tbl_multi_idx ON tbl (location, activity, datetime DESC, usr);

答案 1 :(得分:2)

SELECT * FROM table JOIN (
  SELECT Activity, Location, Max(DateTime) DateTime FROM table
  GROUP BY Activity, Location
  ) m USING (Activity, Location, DateTime)

我最好在没有完全理解你的问题的情况下回答。

答案 2 :(得分:0)

SELECT
   Location,
   User
   Activity
   DateTime
From
   myTable a
   INNER JOIN
   (SELECT Location, User, Max(DateTime) as DateTime FROM myTable GROUP BY Location, User) b
   ON a.Location = b.Location AND a.User = b.User AND a.DateTime = b.DateTime

答案 3 :(得分:0)

select t1.location, t1.user, m.activity, m.datetime 
from table1 t1 inner join
(select activity, max(datetime) datetime from table1 group by activity) m
on t1.activity = m.activity and t1.datetime = m.datetime
order by t1.location asc