我正在尝试声明一个名为NEW_VARIABLE
的变量,它等于(end_date - start_date)
。然后我使用下面的变量NEW_VARIABLE
作为间隔(date1 + NEW_VARIABLE + interval '1 days')
。
CREATE TEMPORARY TABLE tmp1_variables AS (
SELECT
'2016-10-29'::date as start_date,
dateadd(day,-10,getdate())::date as end_date,
'2015-10-31'::date as date1
(end_date - start_date) as NEW_VARIABLE
);
DROP TABLE IF EXISTS tmp_tbl1;
CREATE TEMPORARY TABLE tmp_tbl1 (cobrand_id int, xsum numeric(30,15));
insert into tmp_tbl1 (cobrand_id, xsum )
select q1.cobrand_id, q1.a/q2.d as xsum from (
SELECT cobrand_id, sum(calc) AS a FROM jwn_calc s, tmp1_variables
where s.optimized_transaction_date > start_date AND s.optimized_transaction_date <= end_date + interval '1 days' GROUP BY cobrand_id
) as q1
inner join (
SELECT cobrand_id AS c,
sum(CASE WHEN optimized_transaction_date > date1 AND optimized_transaction_date <= date1 + NEW_VARIABLE + interval '1 days' THEN Calc END) /
sum(CASE WHEN optimized_transaction_date > date1 AND optimized_transaction_date <= date1 + interval '91 days' THEN Calc END) AS d
FROM jwn_calc, tmp1_variables
GROUP BY cobrand_id
) as q2 on q1.cobrand_id = q2.c;
答案 0 :(得分:0)
SQL中根本没有 no 变量。只是表格,列和表达。 所以,显然你不能宣布一个变量&#34;首先。错误的术语很容易激发一种不恰当的方法......
另外,dateadd()
和getdate()
?你可能会想到MS SQL Server。 Postgres中不存在这些功能。
无论哪种方式,使用子查询(或CTE)从常量输入构建新表达式:
CREATE TEMP TABLE tmp1_variables AS (
SELECT *, end_date - start_date AS new_variable
FROM (
SELECT date '2016-10-29' AS start_date
, CURRENT_DATE - 10 AS end_date
, date '2015-10-31' AS date1
) sub
);
显示有效的Postgres语法。
在Postgres中,您只需在integer
(但不是date
)中添加/减去timestamp
。
如果您向interval
添加date
,则会获得timestamp
。
当然,您可以将结果转回date
:
(date1 + new_variable + interval '1 days')::date
而是计算一个date
开头:
date1 + new_variable + 1
除此之外:在Postgres中将不带引号的标识符强制转换为小写。