我是SQL领域的新手,所以这可能是基本的,但我正在尝试根据给定的时间范围获得以前的行(多个)值。
我有一个数据库表(书签),它捕获了所吃的食物,并希望评估给定时间段内所有之前的行,以了解所食用的食物是否导致了过敏。
因此,例如,当我运行以下查询时:
SELECT food_word_1, date, lag(food_word_1,1) OVER (ORDER BY date) as maybe_this FROM bookmark WHERE mood = 'allergies'
结果如下:
food_word_1 | date | maybe_this
-------------+----------------------------+------------
bread | 2018-11-14 09:30:54.272882 |
coffee | 2018-11-15 12:49:46.119737 | bread
beef | 2018-11-15 20:22:51.924697 | coffee
pasta | 2018-11-15 20:23:21.579621 | beef
cereal bar | 2018-11-16 07:53:22.098064 | pasta
red wine | 2018-11-16 09:03:29.589634 | cereal bar
nuts | 2018-11-20 07:43:17.910149 | red wine
duck | 2018-11-21 12:38:31.463169 | nuts
cereal bar | 2018-11-25 09:09:54.187615 | duck
salad | 2018-12-12 21:53:47.258954 | cereal bar
因此,“面包”在“咖啡”(Food_word_1)之前被吃掉/输入(maybe_this) 1行。
我在这里使用滞后函数,但我不确定这是正确的方法,但它显示了我试图实现的大致目标,而不是定义要评估的前几行的确切数量(因此,在本例中使用滞后函数为1),我希望选择36小时的时间段。
感谢您的任何帮助,
md
发布于 2019-02-13 00:18:08
您可以在自左连接后使用stringagg将它们全部列出为一个大列表:
select t1.food_word_1 , t1.date,
string_agg(t2.food_word_1,',') as also_maybe -- make the list
from MyTable t1
left join MyTable t2
on t2.date >= t1.date - (36 * interval '1 hour') -- the previous 36 hours
and t1.food_word_1 <> t2.food_word_1 -- let's ignore the food we've already listed in column 1
and t2.mood = 'allergies' -- limit the results for the list
where t1.mood = 'allergies' -- limit the results for each group
group by t1.food_word_1, t1.date
https://stackoverflow.com/questions/54653961
复制相似问题