Answer the question
In order to leave comments, you need to log in
How to add a column based on a dynamic column?
An example is simple to simplify the understanding of the issue, in a real query it will be difficult to simply write value + 20.
Let's say there is a table table
id | value |
-------------
1 | 20 |
2 | 30 |
Request:
SELECT id, value, value + 10 as value1, value1 + 10 as value2
FROM table;
(SQL: select "articles".*, (select count(*) from "tags" inner join "articles_tags_map" on "tags"."id" = "articles_tags_map"."tag_id" where "articles"."id" = "articles_tags_map"."article_id" and "tags"."title" = tag) as "tags_count",
CASE
WHEN articles.date > now() - interval '1 day' THEN 5
WHEN articles.date > now() - interval '1 week' THEN 3
WHEN articles.date > now() - interval '1 year' THEN 1
ELSE 0
END * 10 as date_value
, date_value + tags_count as test from "articles" where exists (select * from "tags" inner join "articles_tags_map" on "tags"."id" = "articles_tags_map"."tag_id" where "articles"."id" = "articles_tags_map"."article_id" and "tags"."title" = tag)
Answer the question
In order to leave comments, you need to log in
IMHO (didn't check):
CASE... END * 10 as date_value, date_value + tags_count as test
You name the column and try to use this alias right there. Apparently this is exactly what the interpreter does not like.
It works like this:
1. SELECT date_value, date _value*tags_count FROM (SELECT CASE... END as date_value , tags_count FROM "articles" ....)
or like this:
2. SELECT
CASE ... END as date value,
CASE . ... END *tags_count as date_value2
FROM "articles" ....
WITH table1 (id, value) AS (VALUES (1, 10),(2, 20))
SELECT id
, value
, l.value1 AS value1
, l.value1 + 10 AS value2
FROM table1
JOIN LATERAL (SELECT value + 10 AS value1) l ON TRUE
;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question