我有一个这样的查询:
With cte as(
Select min(date1) as min_date,
max(date1) as max_date,
id,
city,
time_id
From some_table
Group by id, city, time_id
),
range as
(select dateadd('month', row_number()over(order by null), (select min_date from cte)) as date_expand
From table(generator (row_count => 12*36))))
Select * from range;
它给出了这个错误: 单行子查询返回多行。
有没有办法在 dateadd 函数的第三个参数中传递变量?因为我的cte会根据group by子句返回很多min_date。 TIA
最佳答案
是的,SELECT 中的子选择只需要返回一行,您的 CTE 中有很多行。
如果你做了这样的事情,你的查询对我来说更有意义:
With some_table as (
SELECT * FROM VALUES
(1, 'new york', 10, '2020-01-01'::date),
(1, 'new york', 10, '2020-02-01'::date),
(2, 'christchurch', 20, '2021-01-01'::date)
v(id, city, time_id, date1)
), cte as (
Select
min(date1) as min_date,
max(date1) as max_date,
id,
city,
time_id
FROM some_table
GROUP BY 3,4,5
), range as (
SELECT
id, city, time_id,
dateadd('month', row_number()over(partition by id, city, time_id ORDER BY null), min_date) as date_expand
FROM table(generator(rowcount =>12*36))
CROSS JOIN cte
)
Select * from range;
但是如果你的 CTE 变成这样:
With cte as (
Select
min(date1) as min_date,
max(date1) as max_date
FROM some_table
), range as (
SELECT
dateadd('month', row_number()over(ORDER BY null), (select min_date from cte)) as date_expand
FROM table(generator(rowcount =>2*4))
)
Select * from range;
这可行,因为只返回一个 min_date 值。
或者您可以找到最小的 min_dates,例如:
WITH cte as (
Select
min(date1) as min_date,
max(date1) as max_date,
id,
city,
time_id
FROM some_table
GROUP BY 3,4,5
), range as (
SELECT
dateadd('month', row_number()over(ORDER BY null), (select min(min_date) from cte)) as date_expand
FROM table(generator(rowcount =>2*3))
)
Select * from range;
关于sql - dateadd函数雪花中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71430946/