简体   繁体   English

SQL 查询 - 查找具有基数大于 1 的字段的记录

[英]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.我只想选择 tester1,因为它在表中为该用户名存在多个术语。

Seems like this should be a pretty simple SQL query, but I'm not able to use any grouping statements to make it work.看起来这应该是一个非常简单的 SQL 查询,但我无法使用任何分组语句来使其工作。

You could use HAVING to filter out rows:您可以使用HAVING过滤掉行:

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.如果您的分配不允许您使用GROUP BY您可以使用ROW_NUMBER()窗口函数来过滤掉行。 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:我会使用带有带有子句的group by

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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