在两个日期之间取最小值时出错

时间:2017-01-09 01:18:04

标签: sql postgresql

DROP TABLE IF EXISTS tmp1_variables;
CREATE TEMPORARY TABLE tmp1_variables AS (
SELECT
    '2016-10-29'::date as start_date,
'2017-01-28'::date as end_date2,
dateadd(day,-13,getdate())::date as end_date);


SELECT cobrand_id, sum(calc) AS a, sum(count) AS b FROM jwn_calc s, tmp1_variables
        where s.optimized_transaction_date > start_date
AND s.optimized_transaction_date <= min(end_date,end_date2) 

我专门在min(end_date,end_date2)收到错误,错误:

  

[42883]错误:函数min(日期,日期)不存在提示:没有函数匹配给定的名称和参数类型。您可能需要添加显式类型转换。

1 个答案:

答案 0 :(得分:3)

使用LEAST()代替MIN()

SELECT cobrand_id,
       SUM(calc) AS a,
       SUM(count) AS b
FROM jwn_calc s
INNER JOIN tmp1_variables t
    ON s.optimized_transaction_date > t.start_date AND
       s.optimized_transaction_date <= LEAST(t.end_date, t.end_date2)

请注意,我已使用显式INNER JOIN替换了隐式联接。作为一般规则,您应该避免在FROM子句中使用逗号。

有关Postgres&#39;的更多信息,请阅读here LEAST()功能