我有一个已发送电子邮件的数据库。列为SendDate
和MailFrom
。发送的每封电子邮件都是记录。
我想制作一份报告,显示过去3个月内按个别月份和来自地址分组的电子邮件数量,例如:
From Adresss Nov 2015 Dec 2015 Jan 2016
clienta@mailer.com 36 28 14
clientb@mailer.com 13 6 8
示例数据只是:
FromAdresss SendDate
clienta@mailer.com 25/11/15
clientb@mailer.com 20/12/15
clientb@mailer.com 21/11/15
我尝试了各种GROUP BY和count方法,但是无法创建动态标头和它们下方的计数。
任何帮助都将不胜感激。
感谢。
答案 0 :(得分:1)
SELECT FromAddress,
SUM( CASE WHEN MONTH(SendDate) = 11 AND YEAR(SendDate) = 2015 THEN 1 ELSE 0 END ) AS Nov2015,
SUM( CASE WHEN MONTH(SendDate) = 12 AND YEAR(SendDate) = 2015 THEN 1 ELSE 0 END ) AS Dec2015,
SUM( CASE WHEN MONTH(SendDate) = 1 AND YEAR(SendDate) = 2016 THEN 1 ELSE 0 END ) AS Jan2016
FROM tableName
GROUP BY FromAddress
我在SQL Server中使用MONTH()和YEAR()函数从SendDate列中提取月份和年份。您可以使用上述查询中使用的DBMS中提供的相应功能。
要使其动态化,您可以使用DATEDIFF()功能,如下所示
SELECT FromAddress,
SUM( CASE WHEN DATEDIFF(MONTH,SendDate,GETDATE()) = 3 THEN 1 ELSE 0 END ) ,
SUM( CASE WHEN DATEDIFF(MONTH,SendDate,GETDATE()) = 2 THEN 1 ELSE 0 END ) ,
SUM( CASE WHEN DATEDIFF(MONTH,SendDate,GETDATE()) = 1 THEN 1 ELSE 0 END )
FROM tableName
GROUP BY FromAddress
答案 1 :(得分:0)
SELECT
COUNT(FromAddress) AS RecordCount,
DATEPART(MM, CONVERT(DATETIME, SUBSTRING(SendDate, 7, 2) + SUBSTRING(SendDate, 4, 2) + SUBSTRING(SendDate, 1, 2), 101)) AS 'MONTH',
DATEPART(YY, CONVERT(DATETIME, SUBSTRING(SendDate, 7, 2) + SUBSTRING(SendDate, 4, 2) + SUBSTRING(SendDate, 1, 2), 101)) AS 'YEAR'
FROM tableName
GROUP BY
DATEPART(MM, CONVERT(DATETIME, SUBSTRING(SendDate, 7, 2) + SUBSTRING(SendDate, 4, 2) + SUBSTRING(SendDate, 1, 2), 101)),
DATEPART(YY, CONVERT(DATETIME, SUBSTRING(SendDate, 7, 2) + SUBSTRING(SendDate, 4, 2) + SUBSTRING(SendDate, 1, 2), 101))
如上所述,但由于你的日期不是标准的SQL,你必须做一些额外的工作