Postgresql 中的递归 CTE

问题描述 投票:0回答:1

当我运行此请求时,我收到错误

递归查询“cte_0”第 1 列在非递归术语中输入日期,但输入没有时区的时间戳第 4 行: select min(to_char(date_trunc('month', day), 'yyyy-mm-d...
^ 提示:将非递归项的输出转换为正确的类型。

在此查询中,“day”列是数据类型为

datetime
的列。

查询:

with recursive cte_0 as
(
    select  min(to_char(date_trunc('month', day), 'yyyy-mm-dd')::date) as dt
    from Transactions
    union all
    select dt + interval '1 month' 
    from cte_0
    where dt < (select  max(to_char(date_trunc('month', day), 'yyyy-mm-dd')::date) from Transactions )
)
select * from cte_0

+----------------+------------+----------+--------+---------------------+
| transaction_id | account_id | type     | amount | day                 |
+----------------+------------+----------+--------+---------------------+
| 2              | 3          | Creditor | 107100 | 2021-06-02 11:38:14 |
| 4              | 4          | Creditor | 10400  | 2021-06-20 12:39:18 |
| 11             | 4          | Debtor   | 58800  | 2021-07-23 12:41:55 |
| 1              | 4          | Creditor | 49300  | 2021-05-03 16:11:04 |
| 15             | 3          | Debtor   | 75500  | 2021-05-23 14:40:20 |
| 10             | 3          | Creditor | 102100 | 2021-06-15 10:37:16 |
| 14             | 4          | Creditor | 56300  | 2021-07-21 12:12:25 |
| 19             | 4          | Debtor   | 101100 | 2021-05-09 15:21:49 |
| 8              | 3          | Creditor | 64900  | 2021-07-26 15:09:56 |
| 7              | 3          | Creditor | 90900  | 2021-06-14 11:23:07 |
+----------------+------------+----------+--------+---------------------+

我想得到:

2021-05-01
2021-06-01
2021-07-01

我尝试更改数据类型,但无法修复此错误

sql postgresql
1个回答
0
投票

如果将

interval
添加到
date
,结果将是
timestamp without time zone
。 PostgreSQL 抱怨这些数据类型不同。

我建议您在 CTE 中使用

timestamp
并在主查询中转换为
date

WITH RECURSIVE cte_0 AS (
    SELECT min(date_trunc('month', day)) AS dt
    FROM transactions

    UNION ALL

    SELECT dt + interval '1 month' 
    from cte_0
    where dt < (SELECT max(date_trunc('month', day)) FROM transactions)
)
SELECT CAST (dt AS date) FROM cte_0;
© www.soinside.com 2019 - 2024. All rights reserved.