我有一个游戏,在数据库中我按日期和时间保存用户操作。时间。
CREATE TABLE user_actions
(
aId BIGSERIAL PRIMARY KEY NOT NULL,
userId BIGINT NOT NULL REFERENCES users(uId) DEFERRABLE INITIALLY DEFERRED,
aDate TIMESTAMP without time zone DEFAULT now(),
aType INTEGER NOT NULL DEFAULT 0
);
我的用户通过电子邮件识别
CREATE TABLE users(
uId BIGSERIAL PRIMARY KEY NOT NULL,
uName VARCHAR (50) NOT NULL,
uEmail VARCHAR (75) UNIQUE NULL
);
每天新增奖品每天都有不同数量的奖品
CREATE TABLE prizes(
pId BIGSERIAL PRIMARY KEY NOT NULL,
pDate TIMESTAMP without time zone DEFAULT now(),
pType INTEGER NULL
pSize INTEGER NULL
);
此查询列出了userId及其每个用户的上一个操作日期
select distinct userId, max(aDate) from user_actions GROUP BY userId order by userId;
我想创建一个查询,该查询将计算自每个用户上次操作以来添加的奖品数量。
我正在跑步:
操作系统:Debian答案 0 :(得分:1)
我想我会使用CTE
虽然尚未经过测试
WITH last_actions AS (
SELECT DISTINCT userId, MAX(aDate) as last_logged
FROM user_actions
GROUP BY userId ORDER BY userId)
SELECT a.userId, COUNT(b.pDate)
FROM last_actions a, prizes b
WHERE b.pDate >= a.last_logged
GROUP BY a.userId;