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

标签 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] ERROR: function min(date, date) does not exist Hint: No function matches the given name and argument types. You may need to add explicit type casts.

最佳答案

使用 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 子句中使用逗号。

阅读here有关 Postgres 的 LEAST() 函数的更多信息

关于sql - 在两个日期之间取最小值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539702/

相关文章:

java - JOOQ:通过主键获取单行?

sql - 如何计算最终总和并计算百分比

Linux 上的 PostgreSQL 10 - LC_COLLATE 语言环境 en_US.utf-8 无效

Python 线程 - 访问 postgreSQL 时崩溃

database - initlocation 在 postgresql 中不起作用

php - SQL查询: do I need two queries or can I use a nested subquery

SQL存储过程转换日期参数

mysql - 在 MySQL 中实现复杂查询

ruby-on-rails - 在 rails 4 中验证 attr_accessor 的标签

SQL - 以列值作为列名的聚合