1

I am using PostgreSQL. I am stuck in building the query. How can we search the result by giving priority to data and discard rest of the data if the any of the priority matched the cases?

Grouping by family wise

If a single person in family has commitment level “VOTER” then it should be fetched rather than other person in the same family whose status are different such as “COMMITTED”, or “REACHOUT”, or “NEUTRAL”

If a single person in the family has commitment level “COMMITTED” then it should be fetched rather than other person in the same family whose status are different such as “REACHOUT” or “NEUTRAL”

This hierarchy follows as “VOTER”, “COMMITTED”, “REACHOUT”, “NEUTRAL” If all the person in the family has the same committed level then the person mobile number if not null should be fetched.

Other are discarded

Sample table with data

ID  COMMITTED LEVEL MOBILE NUMBER   FAMILY NUMBER
1   VOTER               234828288       1
2   COMMITED            262349911       1
3   COMMITED            924792922       2
4   REACHOUT            82639472        2
5   VOTER               79246826234     3
6   VOTER               NULL            3

OUTPUT: result expected

ID  COMMITED LEVEL      MOBILE NUMBER   FAMILY NUMBER
1   VOTER               234828288       1
3   COMMITED            924792922       2
5   VOTER               79246826234     3
1
  • 1
    Don't add tags for products not involved... Commented May 15, 2018 at 12:07

1 Answer 1

3

You can do this using distinct on:

select distinct on (family_number) t.*
from t
order by family_number,
         (case when committed_level = 'Voter' then 1
               when committed_level = 'COMMITTED' then 2
               when committed_level = 'REACHOUT' then 3
               when committed_level = 'Neutral' then 4
               else 5
          end),
         (case when mobile_number is not null then 1 else 2 end);
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.