声明变量并在 AWS redshit 查询中使用

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

我正在尝试声明一个变量并在我的查询中使用。

我有这样的疑问:

INSERT into segmentation (import_date, id, orders, qty, value)
SELECT
    '2024-01-01'::DATE AS import_date,
    td.id,
    COUNT(DISTINCT td.date) AS total_orders,
    SUM(td.qty) AS total_qty,
    SUM(td.amount) AS total_value
FROM
    customer_actions td
WHERE
    td.date_trading_nk <= '2024-01-01'::DATE
GROUP BY
    td.id;

我需要申请但必须使用相同日期的其他条件很少

'2024-01-01'::DATE
。是否可以声明一个参数并使用所有位置而不是硬编码日期

我尝试了以下两个选项来声明它,但它不起作用。

选项#1:

DECLARE param_date DATE := '2024-01-01';

选项#2:

WITH parameter_date AS 
(
    SELECT '2024-02-25'::DATE AS param_date
)
sql amazon-redshift
1个回答
0
投票

您可以使用 CTE 定义参数日期,然后在查询中使用它:

WITH parameter_date AS (
    SELECT '2024-01-01'::DATE AS param_date
)
INSERT INTO segmentation (import_date, id, orders, qty, value)
SELECT
    pd.param_date AS import_date,
    td.id,
    COUNT(DISTINCT td.date) AS total_orders,
    SUM(td.qty) AS total_qty,
    SUM(td.amount) AS total_value
FROM
    customer_actions td
CROSS JOIN
    parameter_date pd
WHERE
    td.date_trading_nk <= pd.param_date
GROUP BY
    td.id;
© www.soinside.com 2019 - 2024. All rights reserved.