我正在尝试获取在广告系列中发送所有电子邮件所花费的总时间。
由于查询中的连接,我最终将'processing_time'列复制到许多行中。因此,运行sum(s.processing_time) as send_time
总是可以代表运行多长时间。
select
c.id,
c.sender,
c.subject,
count(*) as total_items,
count(distinct s.id) as sends,
sum(s.processing_time) as send_time,
from campaigns c
left join sends s on c.id = s.campaigns_id
left join opens o on s.id = o.sends_id
group by c.id;
理想情况下,我想做类似sum(s.processing_time when distinct s.id)
的事情,但我还不太想知道如何实现。
我曾尝试使用case
进行其他尝试,但是我总是遇到相同的问题,我需要根据ID列获取不同的行,但要使用另一列。
答案 0 :(得分:0)
由于您希望统计信息与不同的s.id
和c.id
相关,因此请按两列进行分组。收集所需的(中间)数据,
并将此表用作嵌套子选择查询中的内部表。
在外部选择中,仅按c.id
分组。
由于内部选择分组为s.id
,所以按s.id
进行合计/分组不会对每个c.id
唯一的值进行重复计数。
SELECT id
, sender
, subject
, sum(total_items) as total_items
, sum(sends) as sends
, sum(processing_time) as send_time
FROM (
SELECT
c.id
, s.id as sid
, count(*) as total_items
, 1 as sends
, s.processing_time
, c.sender
, c.subject
FROM campaigns c
LEFT JOIN sends s on c.id = s.campaigns_id
LEFT JOIN opens o on s.id = o.sends_id
GROUP BY c.id, c.sender, c.subject, s.processing_time, s.id) t
GROUP BY id, sender, subject
ORDER BY id
由于最终表包括sender
和subject
,因此您还需要按以下列进行分组,以避免出现诸如以下的错误:
ERROR: column "c.sender" must appear in the GROUP BY clause or be used in an aggregate function
LINE 14: , c.sender