计算sql中的时间戳差异和平均值

时间:2016-03-13 20:26:53

标签: sql postgresql

我在表timestamp中列出了commits列。我试图在最早的时间戳和weesks中的最新时间戳之间找到区别。然后我需要找到每个用户每周的平均提交次数。

在表格中,我有以下列。

id | repo | author_email | author_name | author_date | lines_total

我设法编写了以下查询:

select repo, author_name, author_email, COUNT(author_email) AS COMMITS, SUM(lines_total) AS LINES, MIN(author_date) AS FIRST_COMMIT,
MAX(author_date) AS LAST_COMMIT, TIMESTAMPDIFF(week, MAX(author_date), MIN(author_date)) AS WEEKS
from commits 
where repo='apache.camel'
group by repo, author_name, author_email, author_email 
order by COUNT(author_email) DESC;

TIMESTAMPDIFF无效。如果我删除它,其他一切都很好。我不确定如何才能获得差异和平均值。

错误:

  

错误:列"周"不存在SQL状态:42703字符:182

1 个答案:

答案 0 :(得分:1)

周需要报价。

select repo, author_name, author_email, COUNT(author_email) AS COMMITS, SUM(lines_total) AS LINES, MIN(author_date) AS FIRST_COMMIT,
MAX(author_date) AS LAST_COMMIT, TIMESTAMPDIFF('week', MAX(author_date), MIN(author_date)) AS WEEKS
from commits 
where repo='apache.camel'
group by repo, author_name, author_email, author_email 
order by COUNT(author_email) DESC;

你还需要一个名为timestampdiff的函数,它可以按照你想要的方式处理数周(ISO周?近7周/更短/ 7天的倍数?) mysql有一些名为timestampdiff但没有迹象表明它认为是一周。分数向下舍入为零。

select repo, author_name, author_email, COUNT(author_email) AS COMMITS, SUM(lines_total) AS LINES, MIN(author_date) AS FIRST_COMMIT,
MAX(author_date) AS LAST_COMMIT
, ( MAX(author_date)::date- MIN(author_date)::date )/7 AS WEEKS
from commits 
where repo='apache.camel'
group by repo, author_name, author_email, author_email 
order by COUNT(author_email) DESC;