Skip to content
Advertisement

How to use CASE WHEN in PostgreSQL without adding values to aggregation and GROUP BY?

I need to take one timestamp if my condition is right and other value, if not.

I made such condition:

CASE WHEN tr.type = 'deposit' THEN tr.timestamp::date ELSE tr.status_last_change_timestamp::date END AS timestamp

But PostgreSQL requires to add tr.type to aggregate function or to GROUP BY:

ERROR: column "tr.type" must appear in the GROUP BY clause or be used in an aggregate function

But that’s impossible for me, because I need to take deposits and other transactions in one row of result of query.

How Can I make it? Thanks!

Table tr contains (e.g.): amount, type, timestamp, status_last_change_timestamp

Advertisement

Answer

@MaciejLos gave the solution. In such situation you just need to add tr.type (in my example) to GROUP BY without adding it to SELECT.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement