我希望有人可以在这里查看我的语法。我有一个用户表subscribers
和一个事件表text_alert
。
我希望在2017-07-07
之前和之后分配发送给每个用户的文字提醒总数。
这是我的疑问:
select
subs.id as subscriber_id,
count(t.id) as total_alerts_received,
count(tbefore.id) as before_alerts_received,
count(tafter.id) as after_alerts_received
from subscriber subs
left join text_alert t on t.subscriber_id = subs.id
left join text_alert tbefore on tbefore.subscriber_id = subs.id and tbefore.create_date_time::date <= '2017-07-07'
left join text_alert tafter on tafter.subscriber_id = subs.id and tafter.create_date_time::date > '2017-07-07'
where subs.sms = 0
group by subs.id
我的期望是alerts_received
字段之前和之后的总和与total_alerts_received
匹配。而发生的是3个字段具有相同的值。如果订阅者010
有十个警报,则字段之前和之后也会有10个警报。
要在事实表警告上使用左连接之前和之后拆分。
任何帮助都非常感激。
答案 0 :(得分:3)
ChildComponent
答案 1 :(得分:0)
SELECT
subscriberId,
beforeAlerts,
afterAlerts,
beforeAlerts + afterAlerts as totalAlerts
FROM (
SELECT
DISTINCT subs.id as subscriberId,
(SELECT COUNT(*) FROM text_alert tb WHERE
tb.subscriber_id = subs.id AND
tb.create_date_time <= '2017-07-07') as beforeAlerts,
(SELECT COUNT(*) FROM text_alert ta WHERE
ta.subscriber_id = subs.id AND
ta.create_date_time > '2017-07-07') as afterAlerts
FROM subscriber subs
) AS results;