0

I have this query which selects the count of each "messagecode" based on a defined time interval.

SELECT coalesce(count(case when messagecode = 'F-100' then 'F-100' end), 0) as fixed,
       coalesce(count(case when messagecode = 'H-100' then 'H-100' end), 0) as hope,
       coalesce(count(case when messagecode = 'G-100' then 'G-100' end), 0) as good, 
       coalesce(count(case when messagecode = 'T-100' then 'T-100' end), 0) as todo
       FROM messages WHERE messagetime >= current_timestamp - ('5' * interval '1 minute')

Output for entries

fixed: 115,
hope: 334,
good: 1045,
todo: 6000

I want to make something similar but to select the amount of unique ID's are having this messagecode, I know I should start by doing

SELECT coalesce(count(DISTINCT id), 0) ... 

But my issue is, I don't know yet how to do this for multiple conditions on the same query. Expected output :

fixed: 13, (13 unique ids exist)
hope: 45, (45 unique ids exist)
good: 110, (110 unique ids exist)
todo: 414 (414 unique ids exist)

How will I be able to achieve it?

2
  • 1
    Try count(distinct case when ... then id end) Commented Mar 15, 2016 at 16:18
  • Indeed, many thanks, i never thought by changing the message code with the id @then would make it. You may want to add an answer will accept it. Thanks. Commented Mar 16, 2016 at 7:42

1 Answer 1

1

The query may look like:

SELECT coalesce(count(distinct case when messagecode = 'F-100' then id end), 0) as fixed,
       coalesce(count(distinct case when messagecode = 'H-100' then id end), 0) as hope,
       coalesce(count(distinct case when messagecode = 'G-100' then id end), 0) as good, 
       coalesce(count(distinct case when messagecode = 'T-100' then id end), 0) as todo
       FROM messages WHERE messagetime >= current_timestamp - ('5' * interval '1 minute')
Sign up to request clarification or add additional context in comments.

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.