【问题标题】:Finding whether duplicates exists in 2 select statements查找 2 个 select 语句中是否存在重复项
【发布时间】:2020-11-11 20:58:36
【问题描述】:

能否请您帮助我使用 SQL 语句查找第一个 Select 语句和第二个语句中存在的重复名称。

例如: 我需要查看 1 班的同名学生是否在 2 班或 3 班。

select firstname from College where classid = 1

第二个选择语句是:

select firstname from College where classid in (2, 3)

如果有匹配的任何名称出现,那么我想选择该记录。

【问题讨论】:

  • EXISTS 可以使用。 (sql-server) 或EXISTS 用于 MySQL
  • @Luuk 你能用代码回答吗?谢谢
  • 您需要添加一些表格结构,因为任何答案都可能无法回答您的(家庭作业)问题,因为我怀疑一所大学实际上是否有名字。并查看如何使用 Exists 子句。
  • @Arrow:非常简单!示例在文档中的链接上。

标签: sql sql-server sql-server-2016


【解决方案1】:

加入可能是一种选择

select a.firstname
from
(
select firstname from College where classid = 1
)a join (
select firstname from College where classid in(2,3)
)b on a.firstname=b.firstname

或者,您可以尝试使用exists

select firstname from College c where classid = 1
and exists (select 1 from College c1 where c.firstname=c1.firstname and classid in(2,3))

【讨论】:

    【解决方案2】:

    您可以通过使用带有HAVING 子句的GROUP BY 表达式,例如

    SELECT firstname
      FROM College 
     GROUP BY firstname
    HAVING SUM(CASE WHEN classid = 1 THEN 1 ELSE 0 END) > 0 
       AND SUM(CASE WHEN classid IN (2,3) THEN 1 ELSE 0 END) > 0
    

    只要从每个聚合返回的两个结果都大于零,firstname 值就会在每个集合中重复。

    Demo

    【讨论】:

      【解决方案3】:

      一个非常简单的基于集合的方法是使用intersect:

      select firstname
      from College
      where classid = 1
      intersect
      select firstname
      from College
      where classid in (2, 3);
      

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 2013-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-23
        • 1970-01-01
        • 1970-01-01
        • 2020-01-24
        相关资源
        最近更新 更多