简体   繁体   中英

SQL Query - Find records with field that has cardinality greater than one

I've got a list of records in a table with usernames and school terms. I'd like to find all usernames which have more than one unique school term listed for them in the table overall. So if I had:

Username      Term
-------------------
tester1       19/FA
tester1       19/SP
tester2       19/FA

I would only want to select tester1, since it has more than one term present for that username in the table.

Seems like this should be a pretty simple SQL query, but I'm not able to use any grouping statements to make it work.

You could use HAVING to filter out rows:

select username
from t
group by username
having count(distinct term) > 1

If your assignment does not allow you to use GROUP BY you can use the ROW_NUMBER() window function to filter out rows. For example:

select username
from (
  select 
    username,
    row_number() over(partition by username order by term) as rn
  from t
  ) x
where rn = 2

I would use group by with a having clause:

select username
from t
group by username
having min(term) <> max(term);

If you want all the rows, then use window functions:

select t.*
from (select t.*,
             count(*) over (partition by username) as cnt
      from t
     ) t
where cnt > 1;

Or exists:

select t.*
from t
where exists (select 1 from t t2 where t2.username = t.username and t2.term <> t.term);

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