I have a table containing parent_ids, advertiser_ids and number values. I want to write a query that gives me the parent ids where all advertisers under that parent have a number value greater than 90.

I'm struggling to do this in a streamlined way. I've been trying an assortment of queries, but I'm worried my answer is missing some output values (still testing):

SELECT parent
FROM tbl_a
HAVING sum(case when num_dark_days BETWEEN 90 AND 120 
                then 1 else 0 end
          ) = count(advertiser_id)
parent  advertiser  num_dark_days
A           1               5
A           2               50
A           3               40
A           4               90
A           5               130
B           6               95
B           7               99
B           8               200
B           9               102
C           10              89
D           11              96

I want to get back something that looks like this:

parent      full_dark
A             no
B             yes
C             no
D             yes

(using the logic of this ‘pretend' in between table)

parent    num_dark_advertisers    total_advertiser_per_parent
A            2                    5
B            4                    4
C            0                    1
D            1                    1

I think you just need a CASE expression, such as:

SELECT parent,
       (CASE WHEN COUNT(*) FILTER (num_dark_days >= 90)
             THEN 'yes' ELSE 'no'
FROM tbl_a
GROUP BY parent;

Few corrections from the other user's answer:

SELECT parent,
                   WHEN num_dark_days >= 90 
                   THEN 1 
                   ELSE 0 
                   END) = COUNT(advertiser_id)
             THEN 'yes' ELSE 'no'
        END) AS 'full_dark'
FROM tbl_a
GROUP BY parent;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.