在WHERE子句中减去日期

时间:2013-06-07 06:13:28

标签: sql postgresql datetime

我有以下查询

`SELECT t.client_id, 
 count(t.client_id) as trips_xdays
 FROM trips t
 JOIN users u ON t.client_id = u.usersid
 WHERE t.city_id = 12
 AND t.status = 'completed'
 AND ( date_trunc('day',t.dropoff_at) - date_trunc('day',u.creationtime) <= 30 days,    0:00:00)
 GROUP BY t.client_id`

并且当我尝试通过&lt; = 30天,0:00:00约束查询时出错。但是我认为自从我查询以来这将是正确的格式

 `select date_trunc('day',t.dropoff_at) - date_trunc('day',u.creationtime)
 from trips t 
 inner join users u ON t.client_id = u.usersid`

单独返回,回复的格式为30天,0:00:00

有关如何正确查询的任何建议,以便我可以在&lt; = 30天内限制查询?

3 个答案:

答案 0 :(得分:3)

假设我们正在处理数据类型timestamp,您可以简化:

SELECT t.client_id, count(t.client_id) AS trips_xdays
FROM   trips t
JOIN   users u ON t.client_id = u.usersid
WHERE  t.city_id = 12
AND    t.status = 'completed'
AND    t.dropoff_at::date < u.creationtime::date + 30
GROUP  BY 1;

到目前为止,简单的广告素材较短,您只需将integer添加到date即可。

或者稍微不同的结果和更快的执行:

...
AND    t.dropoff_at < u.creationtime + interval '30 days'

最后一种形式可以更容易地使用普通索引。它测量30天完全

答案 1 :(得分:0)

看起来我只是忘了引号。其工作顺序中的查询是:

SELECT t.client_id, 
count(t.client_id) as trips_xdays
FROM trips t
JOIN users u ON t.client_id = u.usersid
WHERE t.city_id = 12
AND t.status = 'completed'
AND ( date_trunc('day',t.dropoff_at) - date_trunc('day',u.creationtime) <= '30 days,      0:00:00')
GROUP BY t.client_id

答案 2 :(得分:0)

从头顶写下来,请验证正确性:

`SELECT t.client_id, 
 count(t.client_id) as trips_xdays
 FROM trips t
 JOIN users u ON t.client_id = u.usersid
 WHERE t.city_id = 12
 AND t.status = 'completed'
 AND ( DATEDIFF(day,t.dropoff_at,u.creationtime) <= 30)
 GROUP BY t.client_id`

我还想补充一点,虽然我对date_trunc方法不够熟悉,但使用<= 30 days似乎是一个很大的语法错误,应该使用30,将输出组合看起来像没有字符串的30后缀。

为了使事情更清楚,比较字符串以实际比较数字是恕我直言的不良做法。

日期使用的来源:

date diff usages

other related tips