我正在尝试使用MSSQL Express 2005获取在日期范围内收到的电子邮件数量。我已经管理了那么多,但现在我想将数据拆分成用它完成的工作。
这是我到目前为止所得到的:
SELECT EmailAddress, COUNT(EmailAddress)
FROM mails
WHERE ReceivedTime >= DATEADD(DAY, -7, GETDATE())
GROUP BY EmailAddress
HAVING COUNT(EmailAddress) > 10
这给了我一个上周邮寄超过10次的地址列表,但是我们还有另一个列告诉我们邮件发生了什么。我正在努力实现这样的目标:
SELECT EmailAddress,
COUNT(ActionTaken WHERE ActionTaken="Deleted") AS Deleted,
COUNT(ActionTaken WHERE ActionTaken="Replied") AS Replied,
COUNT(ActionTaken WHERE ActionTaken="Read") AS Read,
COUNT(EmailAddress) AS Total
FROM mails
WHERE ReceivedTime >= DATEADD(DAY, -7, GETDATE())
GROUP BY EmailAddress
HAVING COUNT(EmailAddress) > 10
我正在寻找这些行的结果集:
EmailAddress | Deleted | Replied | Read | Total
---------------------------------------------------
user1@domain.com | 4 | 5 | 3 | 12
user2@domain.com | 2 | 6 | 3 | 11
我很确定它与使用OVER(PARTITION BY)子句有关,但我遇到了障碍。我意识到ActionTaken字段并不理想,但我没有构建它!
答案 0 :(得分:3)
对字符串文字使用单引号,因此无论QUOTED_IDENTIFIER
设置如何,它都可以正常工作。
SELECT EmailAddress,
Sum(CASE WHEN ActionTaken = 'Deleted' THEN 1 ELSE 0 END) AS Deleted,
Sum(CASE WHEN ActionTaken = 'Replied' THEN 1 ELSE 0 END) AS Replied,
Sum(CASE WHEN ActionTaken = 'Read' THEN 1 ELSE 0 END) AS [Read],
Count(EmailAddress) AS Total
FROM mails
WHERE ReceivedTime >= Dateadd(DAY, -7, Getdate())
GROUP BY EmailAddress
HAVING Count(EmailAddress) > 10
答案 1 :(得分:1)
SELECT EmailAddress,
COUNT(CASE WHEN ActionTaken = 'Deleted' THEN ActionTaken END) AS Deleted,
COUNT(CASE WHEN ActionTaken = 'Replied' THEN ActionTaken END) AS Replied,
COUNT(CASE WHEN ActionTaken = 'Read' THEN ActionTaken END) AS [Read],
COUNT(EmailAddress) AS Total
FROM mails
WHERE ReceivedTime >= DATEADD(DAY, -7, GETDATE())
GROUP BY EmailAddress
HAVING COUNT(EmailAddress) > 10