简体   繁体   中英

How to get all rows that has same ID but diffrent value in other column?

I'm having a trouble writing a query in PostgreSQL. I have a View that contains IDs with subID . for example:

ID  quantity partID 
100   50       10
100   20       10
100   30       11
101   50       13
101   70       13
102   20       17

I want to get all rows that has same ID but different partIDs . for the given example I would like to get:

ID  quantity partID 
100   50       10
100   20       10
100   30       11

i tried this query query:

select id  ,quantity ,partid 
from A
group by id,quantity,partid
having count(id)>2
order by id

but it doesn't work. It accualty checks if ID appears in more than 2 rows... in the given example it will take ID 101 as well. I also don't know how to make it choose only partid which are diffrent per ID .

You can count only distinct partid within each id group:

select * 
from A t 
where exists (
  select 1
  from A
  where id = t.id
  having count(distinct partid) > 1)

SQLFiddle

You don't need to count; you only have to check if a row with a different partid exists:

SELECT * 
FROM atable t 
WHERE EXISTS (
  SELECT *
  FROM atable x
  WHERE x.id = t.id
  AND x.partid <> t.partid
  );

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