在SQL中计算日期间隔

时间:2012-01-31 20:42:53

标签: mysql sql date

我有date, name, counts

等数据

如何获取每个名字的第一个和最后一个日期之间的日期间隔?

SELECT name, SUM(counts), MAX(date)-MIN(date) AS age //this is wrong
FROM tb
GROUP BY name

2 个答案:

答案 0 :(得分:1)

SELECT name
     , SUM(counts)
     , DATEDIFF(MAX(date), MIN(date))/365 AS age1  --- may need adjustment
     , YEAR(MAX(date)) - YEAR(MIN(date))  AS age2  --- integer result
FROM tb
GROUP BY name

答案 1 :(得分:1)

SELECT name, SUM(counts), DATEDIFF(MAX(date),MIN(date)) as age
FROM tb
GROUP BY name