我正在运行Postgres 9.6。我有一个用户表:
id | integer | | not null | nextval('user_id_seq'::regclass)
name | character varying | | not null |
我有一个action
表:
actioned_by | integer | | |
category | character varying | | not null |
t_actioned | timestamp without time zone | | not null |
我有一个查询,指示用户过去30天中有多少天处于活动状态:
SELECT d.actioned_by, COUNT(*) AS cnt FROM
(SELECT date_trunc('day', t_actioned) AS day, actioned_by
FROM history
GROUP BY day, actioned_by) d
GROUP BY actioned_by
ORDER BY cnt DESC;
但是有什么方法可以用此值注释每个用户,还是创建引用它的简便方法?
如果我可以执行“让我每月在活动中超过5天的所有法国用户”这样的事情,而不必每次都键入以上所有内容,那将非常有用。
也许我需要一个视图?
答案 0 :(得分:0)
推荐的方法 进行查看。
但是您也可以在复合类型(一种虚拟列)上创建函数:
-- Virtual column is a function that has a table type in its signature
CREATE FUNCTION last_activity("user") RETURNS text AS $$
SELECT d.actioned_by, COUNT(*) AS cnt FROM
(SELECT date_trunc('day', t_actioned) AS day, actioned_by
FROM history
--Filter
WHERE actioned_by = $1.id
GROUP BY day, actioned_by) d
GROUP BY actioned_by
ORDER BY cnt DESC;
$$ LANGUAGE SQL;
--In order to use virtual columns you must qualify it with table name/alias
SELECT u.last_activity, * FROM "user" u;
更多信息here。