我有EmailEvent
表。这是存储打开和单击的STI表(使用type
属性)。我现在有这个代码,提供有关使用收件人地址(email_address
字段)的电子邮件数量的信息:
EmailEvent.where("type = 'OpenEmailEvent' OR type = 'ClickEmailEvent'")
.where(email_id: email_ids).happened_between_dates(start_date, end_date)
.select("email_address, count(distinct email_id) as emails_count")
.group(:email_address).reorder(nil)
它会生成这样的代码:
SELECT email_address, count(distinct email_id) as emails_count
FROM "email_events"
WHERE "email_events"."deleted_at" IS NULL
AND (type = 'OpenEmailEvent' OR type = 'ClickEmailEvent')
AND "email_events"."email_id" IN (85487, 75554, 85489, 77184, 78562, 75587, 82879, 85535, 85534)
AND (created_at between '2017-02-28 22:52:01.000000' AND '2017-03-29 05:59:59.000000')
GROUP BY "email_events"."email_address"
我需要提供每个email_address
的打开和点击次数的信息。我无法使用count(id)
,因为它会给我打开和点击,因此我需要以某种方式使用type
属性,但我无法弄清楚它应该如何工作。有人可以给我建议我该怎么办?
答案 0 :(得分:2)
替换此
count(distinct email_id) as emails_count
类似于使用case或IIF的SQLServer
sum(case when type = 'OpenEmailEvent' then 1 else 0 end) [Opens],
sum(case when type = 'ClickEmailEvent' then 1 else 0 end) [Click],