如何从单个列创建日期范围?

时间:2013-08-07 22:28:30

标签: sql sql-server

我正在尝试查询具有这些参数的数据库:

Transaction Date, User Email Address

我想要的结果表是这些参数:

Email Address, dateDiff

对于dateDiff,我想找出最早的交易日期和最近的交易日期之间的差异。

我将如何做到这一点?

我的代码(显然不正确)

SELECT [Email Address], DATEDIFF(day, [Transaction Date],[Transaction Date]) AS 'dateDiff'
FROM [DB].[TABLE]
ORDER BY [dateDiff] Desc

1 个答案:

答案 0 :(得分:4)

在执行datediff()之前,您需要一个聚合来获取每封电子邮件的最小值和最大值:

SELECT [Email Address],
       DATEDIFF(day, min([Transaction Date]), max([Transaction Date])) AS 'dateDiff'
FROM [DB].[TABLE]
GROUP BY [Email Address]
order by 2 desc;