我有这样的数据:
person_id date1
1 2016-08-03
1 2016-08-04
1 2016-08-07
我想要的结果是person_id的所有日期之间的最小差异,在这种情况下,最小差异是1天(8/3和8/4之间)。
有没有办法在redshift中查询按person_id分组的内容?
谢谢!
答案 0 :(得分:4)
我认为你想要每个人都这样。如果是,请使用lead()
或select person_id, min(next_date1 - date1)
from (select t.*,
lead(date1) over (partition by person_id order by date1) as next_date1
from t
) t
group by person_id;
和聚合:
{{1}}
答案 1 :(得分:1)
SELF JOIN
应该对你有用。试试这种方式
SELECT a.date1 - b.date1
FROM table1 a
JOIN table1 b
ON a.person_id = b.person_id
AND a.date1 <> b.date1
Where a.date1 - b.date1 > 0
ORDER BY a.date1 - b.date1 ASC
LIMIT 1
答案 2 :(得分:1)
这个使用自联接来比较每个日期:
SELECT t1.person_id, MIN(datediff(t1.date1, t2.date1)) AS difference
FROM t t1
INNER JOIN t t2
ON t1.person_id = t2.person_id
AND t1.date1 > t2.date1
GROUP by t1.person_id