1

I have a query

SELECT 
        cd.signoffdate,
        min(cmp.dsignoff) as dsignoff
      FROM clients AS c 
      LEFT JOIN campaigns AS cmp ORDER BY dsignoff;

If I want to have something like this built into the postgres query will it work and how do I do it

if the cd.signoffdate is empty it should take min(cmp.dsignoff) as dsignoff as the value and then order by this column, so in other words it should order by dsignoff and cd.signoffdate and tread it as one column, is this possible and how?

3 Answers 3

2

Your query could look like this:

SELECT c.client_id, COALESCE(c.signoffdate, min(cmp.dsignoff)) AS signoff
FROM   clients c 
LEFT   JOIN campaigns cmp ON cmp.client_id = c.client_id  -- join condition!
GROUP  BY c.client_id, cd.signoffdate                     -- group by!
ORDER  BY COALESCE(c.signoffdate, min(cmp.dsignoff));

Or, with simplified syntax:

SELECT c.client_id, COALESCE(c.signoffdate, min(cmp.dsignoff)) AS signoff
FROM   clients c 
LEFT   JOIN campaigns cmp USING (client_id)
GROUP  BY 1, cd.signoffdate
ORDER  BY 2;

Major points:

  • Used alias c, but referenced as cd.
  • No join condition leads to cross join, probably not intended.
  • Missing GROUP BY.
  • I assume that you want to group by the primary key column of clients and call it client_id.
  • I also assume that client_id links the two tables together.
  • COALESCE() serves as fallback in case signoffdate IS NULL.
Sign up to request clarification or add additional context in comments.

Comments

0
  ORDER BY coalesce(cd.signoffdate, min(cmp.dsignoff));

But don't you need some GROUP BY in your original query?

Comments

0

You can use COALESCE

SELECT COALESCE(cd.signoffdate, min(cmp.dsignoff)) as dsignoff

I'm not sure if you can order by coalesce in Postgres - might be worth just ordering by both columns

Comments

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.