count(*)条记录按两个表的日期分组

时间:2016-11-29 17:07:58

标签: sql sql-server-2008 join union

我有两张桌子:

emailLog 表格:

email           sendTime                   sourceTag
-------------------------------------------------------
yadda@aol.com   2016-11-17 09:14:37.213    WelcomeEmail
badda@aol.com   2016-11-16 09:14:37.213    WelcomeEmail
test@aol.com    2016-11-15 09:12:33.213    WelcomeEmail

注册表:

email           dateRegistered             regSource
-------------------------------------------------------
yadda@aol.com   2016-11-17 09:14:37.213    WelcomeEmail
badda@aol.com   2016-11-16 09:14:37.213    WelcomeEmail
test@aol.com    2016-11-15 09:12:33.213    WelcomeEmail

我尝试执行合并查询,以显示在给定日期收到电子邮件的人的COUNT()与在给定日期注册的人的COUNT()相比

我已经达到了这个目的:

SELECT
    CONVERT(varchar(10), sendTime, 120) as date,
    COUNT(*) as numberSent 
    FROM emailLog
WHERE sourceTag = 'WelcomeEmail'
AND
sendTime BETWEEN '20161110' and '20161120'
GROUP BY
    CONVERT(varchar(10), sendTime, 120)
ORDER BY DATE ASC;

其中列出了使用特定sourceTag发送的电子邮件列表,按日期分组:

DATE                NUMBERSENT
2016-11-17          256
2016-11-18          136
2016-11-19          40
2016-11-20          118
2016-11-21          186

但我无法弄清楚如何加入该日期的注册总数+与该来源,例如:

DATE                NUMBERSENT    MEMBERSREGISTERED
2016-11-17          256           12
2016-11-18          136           24
2016-11-19          40            13
2016-11-20          118           2
2016-11-21          186           11

我曾试图做过......

SELECT 
 (SELECT count(*) from emailLog) 
    as emailLogResults, 
 (select count(*) from registrations) 
    as registrationResults
    ...

但在那之后我被困住了。非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

为了简单明了,我认为,您可以创建2个临时表。第一个将包含使用特定sourceTag发送的电子邮件列表,按日期分组,如您所做的那样。第二个表格将对注册做同样的事情。你可以比内部加入2个临时表。

答案 1 :(得分:0)

使用两个表,您可以使用full join(在任何一个表中的特定日期没有行时从另一个表中获取行),然后使用条件聚合。

SELECT
    COALESCE(CONVERT(varchar(10), e.sendTime, 120),CONVERT(varchar(10), r.dateRegistered, 120)) as date,
    COUNT(e.email) as numberSent,
    COUNT(r.email) as membersRegistered
FROM emailLog e
FULL JOIN registrations r ON e.sendTime = r.dateRegistered
AND e.sourceTag = 'WelcomeEmail'
AND r.regSource = 'WelcomeEmail'
AND e.sendTime BETWEEN '20161110' and '20161120' 
AND r.dateRegistered BETWEEN '20161110' and '20161120'
GROUP BY COALESCE(CONVERT(varchar(10), e.sendTime, 120),CONVERT(varchar(10), r.dateRegistered, 120))
ORDER BY DATE ASC