我有一个如下所示的数据库:
person | product | purchase_time
-------+------------+---------------------
jim | football | 2013-02-28 00:01:00
jane | basketball | 2013-02-28 01:01:00
ben | baseball | 2013-02-28 02:02:00
jim | basketball | 2013-02-28 00:01:00
jim | basketball | 2013-02-28 00:03:00
jim | football | 2013-02-28 00:04:00
jane | baseball | 2013-02-28 00:05:00
jane | football | 2013-02-28 00:08:00
jane | basketball | 2013-02-28 01:03:00
ben | baseball | 2013-02-28 03:02:00
我需要一份报告来告诉我“人”购买任何两种产品的两个最近日期之间的差异(以秒为单位)。
所以,例如,如果我使用足球和篮球,我需要知道类似的东西:
jim | 60
jane | 3180
结果来自吉姆最近的足球和篮球购买相隔60秒(04:00和03:00),jane的足球和篮球购买时间为3180秒(08:00,分别是01:03。
我可以通过循环逐个人进行此操作,我可以使用如下查询:
SELECT a.person,
abs(DATE_PART('epoch', a.purchase_time - b.purchase_time)
FROM
(SELECT *
FROM mytable
WHERE person = 'jim'
AND product = 'football'
ORDER BY purchase_time LIMIT 1) a,
(SELECT *
FROM mytable
WHERE person = 'jim'
AND product = 'basketball'
ORDER BY purchase_time LIMIT 1) b
但为了查看每个人的结果,我必须通过循环执行此查询。
我确信有更明智的方法可以做到这一点,我只是不知道它是什么。
任何人都可以提供任何建议吗?我正在使用Postgres 8.1.23。
答案 0 :(得分:1)
这是你想要的吗?
select person, abs(DATE_PART('epoch', p1 - p2)
from (select person,
MAX(case when product = 'football' then purchase_time end) as p1,
MAX(case when product = 'basketball' then purchase_time end) as p2
from mytable
group by person
) p
where p1 is not null and p2 is not null
我将此问题解释为最近购买的产品A和最新的产品B,而不是最近的两种产品(例如,可能都是产品A)。