我有以下观点:
CREATE OR REPLACE VIEW view_a AS
SELECT distinct p.partid, case when
(SELECT EXTRACT(YEAR FROM age) * 12 + EXTRACT(MONTH FROM age)
FROM age(NOW(), LEAST(pp.createdate)) AS t(age)) AS months_between
<24 then months_between::integer else 24 end as timeframe
FROM ....
WHERE ....;
此视图需要createdate
(每个partid
最早记录的创建日期的时间戳)并计算自此日期以来经过的月份NOW()
与完成here相同
如果结果小于24(月)我想要这个结果,否则我想要24。
目前无效,它在案件中间不接受AS months_between
。
我该怎么做?
编辑:
例如,此查询有效:
SELECT distinct p.partid, case when
(SELECT EXTRACT(YEAR FROM age) * 12 + EXTRACT(MONTH FROM age)
FROM age(NOW(), LEAST(pp.createdate)) AS t(age))
<24 then 5 else 24 end as timeframe
FROM ....
WHERE ....;
然而它会返回5或24而且它不是我想要的。我希望它返回CASE中计算的值。
为简化问题,基本上表格是:
case when calculated_value < 24 then calculated_value else 24 end;
我希望能够在案例中返回calculated_value。
答案 0 :(得分:1)
你可以尝试将个月_在计算之间移动到common table expression(WITH查询),如下所示:
WITH timeframe_table AS (
SELECT EXTRACT(YEAR FROM age) * 12 + EXTRACT(MONTH FROM age)
FROM age(NOW(), LEAST(pp.createdate)) AS months_between
) SELECT
CASE when months_between< 24 then months_between else 24 as timeframe
FROM ..., timeframe_table
WHERE...
您可能需要在timeframe_table中添加一些id字段,以便与您的表有一些连接条件。