(很抱歉,如果我没有正确设置问题的格式,这是我的第一篇文章)。
我有以下示例数据:
a.label | b.recipient_id| b.action|b.creation_date
Books | Recipient1 | 0 | 01/04/2018
Books | Recipient1 | 1 | 02/04/2018
Books | Recipient1 | 0 | 03/04/2018
Books | Recipient1 | 1 | 04/04/2018
Books | Recipient2 | 1 | 05/04/2018
Books | Recipient2 | 0 | 06/04/2018
Books | Recipient2 | 0 | 07/04/2018
Books | Recipient2 | 1 | 08/04/2018
Books | Recipient3 | 1 | 13/04/2018
Books | Recipient3 | 0 | 14/04/2018
Books | Recipient3 | 1 | 15/04/2018
Books | Recipient3 | 0 | 16/04/2018
我想计算max(creation_date)操作= 1的收件人ID
如果对于max(creation_date)操作等于0,则我根本不想计算此收件人。
因此,在上面的示例数据中,我想计算Recipient1和Recipient2,而不是Recipient3。
我尝试了以下关注方式,但到目前为止没有任何效果
SELECT count(b.recipient_id)
FROM Services a, Subscriptions b,
(SELECT recipient_id,MAX(creation_date)
FROM Subscriptions
GROUP BY recipient_id) c
WHERE a.SERVICE_ID = b.SERVICE_ID
AND b.recipient_id = c.recipient_id
AND b."ACTION" = '1'
AND a.LABEL = 'Books'
预先感谢
答案 0 :(得分:0)
这是一种使用两种聚合级别的方法:
select count(*)
from (select su.recipient_id
from services se join
subscriptions su
on se.service_id = su.service_id
where se.label = 'BOOKS'
group by su.recipient_id
having max(su.creation_date) = max(case when su.action = 1 then su.creation_date)
) ss;
having
子句检查最终状态为1
。
注意:
FROM
子句中使用逗号。JOIN
语法。