A
A
Alexey Bille2018-09-14 12:35:52
PostgreSQL
Alexey Bille, 2018-09-14 12:35:52

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;

Real request
(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)

Error: Undefined column: 7 ERROR: column "date_value" does not exist

Error: ERROR: column "value1" does not exist
Is there any way to make this query work?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Bille, 2018-09-14
@alexey_bille

I asked the same question on stackoverflow

P
ponaehal, 2018-09-17
@ponaehal

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" ....

K
kylemaclohlan, 2018-10-01
@kylemaclohlan

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 question

Ask a Question

731 491 924 answers to any question