简体   繁体   中英

Query to return row values which has same values in all the rows for each different value of one column

For Example, I have the following data :

示例截图

I want to display only 2nd, 3rd, 5th row because all the A1, A2, A3, A4 values are the same for each A6 in (01, 02, 03) (each row must have each A6 value). So I want to exclude only the 4th column.

I understand that you want records for which values 1 , 2 and 3 are all available for a given (a1, a2, a3, a4) tuple.

Here is one way to do it by joining the table with an aggregate subquery:

select t.*
from mytable t
inner join (
    select a1, a2, a3, a4
    from mytable t1
    where a6 in (1, 2, 3)
    group by a1, a2, a3, a4
    having count(distinct a6) = 3
) g 
    on  g.a1 = t.a1 
    and g.a2 = t.a2 
    and g.a3 = t.a3 
    and g.a4 = t.a4

You can also filter with a correlated subquery:

select t.*
from mytable t
where (
    select count(distinct a6) 
    from mytable t1
    where t1.a1 = t.a1 and t1.a2 = t.a2 and t1.a3 = t.a3 and and t1.a4 = t.a4
) = 3

If you want the rows where A2/A3/A4 have duplicates, then you can use window functions:

select t.*
from (select t.*,
             count(distinct (case when a6 in (1, 2, 3) then a6 end) over (partition by a2, a3, a4) as cnt
      from t
     ) t
where cnt > 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM