0

I have a query where I am using CASE statement inside DISTINCT ON like this:

SELECT
    DISTINCT ON(COALESCE(users.cuid,events.uid),
        CASE WHEN events.props->>'prop' IS NULL THEN '$none' WHEN events.props->>'prop' = '' THEN '$none' ELSE events.props->>'prop' END)
    COALESCE(users.cuid, events.uid) as coal_user_id,
    CASE WHEN events.props->>'prop' IS NULL THEN '$none' WHEN events.props->>'prop' = '' THEN '$none' ELSE events.props->>'prop' END AS _group_key_0, events.uid as event_uid
FROM events JOIN users ON events.uid=users.id 
WHERE events.project_id='<>' AND timestamp>='<>' AND timestamp<='<>'
ORDER BY coal_user_id, _group_key_0, events.timestamp ASC

On running, I am getting this error:

SELECT DISTINCT ON expressions must match initial ORDER BY expressions

I tried using alias like as _group_key_0 inside distinct on clause, but that again was throwing error a different error.

Is there a way to use CASE statements in distinct on and make this work?

1 Answer 1

2

You have to add the expressions from the DISTINCT ON clause at the beginning of the ORDER BY clause, like the error message says:

SELECT DISTINCT ON(COALESCE(users.cuid,events.uid),
                   CASE WHEN events.props->>'prop' IS NULL THEN '$none'
                        WHEN events.props->>'prop' = '' THEN '$none'
                        ELSE events.props->>'prop'
                   END)
       COALESCE(users.cuid, events.uid) as coal_user_id,
       CASE WHEN events.props->>'prop' IS NULL THEN '$none'
            WHEN events.props->>'prop' = '' THEN '$none'
            ELSE events.props->>'prop'
       END AS _group_key_0,
       events.uid as event_uid
FROM events JOIN users ON events.uid=users.id 
WHERE events.project_id='<>'
  AND timestamp>='<>'
  AND timestamp<='<>'
ORDER BY COALESCE(users.cuid,events.uid),
         CASE WHEN events.props->>'prop' IS NULL THEN '$none'
              WHEN events.props->>'prop' = '' THEN '$none'
              ELSE events.props->>'prop'
         END,
         events.timestamp ASC;
Sign up to request clarification or add additional context in comments.

1 Comment

Writing complete CASE in ORDER BY worked actually. While experimenting, for coal_user_id, just writing ORDER BY coal_user_id was working so I was expecting it to work with _group_key_0 as well in similar way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.