Postgres查询:根据用户活动对用户排名

时间:2014-04-01 00:06:05

标签: sql postgresql aggregate

在最新版本的PostgreSQL中,给出了为社交媒体参数应用程序创建的以下表格,

CREATE TABLE Users (
  name varchar PRIMARY KEY,
  email varchar NOT NULL,
  password varchar NOT NULL
);

CREATE TABLE Topic (  
  id integer PRIMARY KEY,
  text varchar NOT NULL,  -- a controversial statement to be argued about
  creator varchar REFERENCES Users (name),
  postdate date NOT NULL
);

CREATE TABLE Argument (   
  id integer,
  topic integer REFERENCES Topic (id), -- statement argument is based on
  startdate date NOT NULL,             -- date argument started
  enddate date NOT NULL,               -- date argument ended
  PRIMARY KEY (id, topic)              -- weak entity, depends on statement
);

我正在尝试编写一个函数或查询,对于给定的用户,将根据用户发布的该主题的参数数量对他/她参与的主题进行排名,这样网站最终可以优先考虑用户的哪些参数先看看。我知道它涉及聚合,但我不确定如何正确连接关系。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

select name, topic.id as topic_id, count(*) as total_arguments
from
    argument a
    inner join
    topic t on t.id = a.topic
    inner join
    users u on u.name = t.creator
where name = _name
group by name, topic.id
order by total_arguments desc

答案 1 :(得分:0)

如果您为引用author的{​​{1}}添加Argument,则可以执行以下操作:

Users.name

并添加SELECT Users.name, count(Argument.id) as arg_count, Topic.text FROM Users INNER JOIN Argument ON Users.name = Argument.author INNER JOIN Topic ON Topic.id = Argument.topic GROUP BY Users.name, Topic.text ORDER BY arg_count DESC; 以获取一个用户的列表。

您可以在http://sqlfiddle.com/#!15/d98ea/10

上查看