简体   繁体   中英

SQL to find common traits among all users

I'm trying to retrieve just the common traits from all the users.

  User(u)Trait(t)
  u1      t1
  u1      t2
  u1      t3
  u2      t2
  u2      t3
  u2      t4
  u3      t2
  u3      t3
  u3      t4

示例数据集

I'm trying to join the table to itself but not getting the desired output.

I expect the output of the above to be t2 and t3 and these are the only traits that are present in all the 3 users.

You can use aggregation:

select ut.trait
from usertraits ut
group by ut.trait
having count(*) = (select count(distinct ut2.user) from usertraits ut2);

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