Search code examples
mysqlsqlsubqueryaggregate-functionswhere-clause

SQL Select one value but take in account other values as well


This is what a table looks like

Number   UniqID   status
555      1        in
555      1        in
555      1        in
555      2        in
555      2        out
555      2        in

I would like to select like this

Number   UniqID   status
555      1        in
555      1        in
555      1        in

and only select it like that if all the same uniqIDs have status in. if one of the status says out for the same ID skip the entire thing. Also the UniqID is automatically generated

and would like to display it like

Number    status
555       in

Solution

  • You can get the first resulset with not exists:

    select *
    from mytable t
    where 
        t.status = 'in' 
        and not exists (
            select 1 
            from mytable t1 
            where t1.number = t.number and t1.uniqid = t.uniqid and t1.status = 'out'
        )
    

    On the other hand, if you want all (number, uniqid) tuples for which all statuses are "in", aggregation is simpler:

    select number, uniqid, min(status) as status
    from mytable
    group by number, uniqid
    having min(status) = max(status) and min(status) = 'in'