[Answered ]-Django : Writing a query with condition referencing aggregation within same table

1πŸ‘

βœ…

It’s fairly straightforward if you use a little subquery:

select
    name,
    sum(count)
from sample s
where flag = false
and (added > (select max(added)
    from sample
    where name = 'abcd1'
    and flag = true)
    OR
    not exists (
        select *
        from sample
        where name = 'abcd1'
        and flag = true)
    )
and name = 'abcd1'

Note the use of the OR not exists clause to handle the case when there are no entries with flag=true.

1πŸ‘

How about

select name, sum(count) as count
from T as t
where flag = 'false'
and exists (
    select 1
from T
where name = t.name
and flag = 'true'
group by name, flag
having max(added) < t.added
)
group by name

Leave a comment