识别两个不同列中具有两个相同值的记录?

时间:2015-07-01 22:51:27

标签: sql oracle duplicates

我有一张学生ID,major1,major2和minor的表格。我想确定那些为同一专业注册两次的学生的记录。我需要一个功能来只选择那些拥有相同专业的人,比如" FIN"在Major1和Major2列中。我到目前为止:

CREATE VIEW A5T5 AS
SELECT (firstname || ' ' || lastname)"FullName", StudentID AS "StudentID", Major1 as "DoubleDipping"
FROM A5
Group by Major1, Major2 ?????
Having count ?????
ORDER BY Major,LastName,FirstName;

2 个答案:

答案 0 :(得分:1)

为什么它不像以下那样简单:

SELECT firstname,lastname FROM A5 WHERE Major1 = Major2

答案 1 :(得分:1)

我认为你正在努力使这比现在更难。如果我正确理解您的问题,以下查询应该会为您提供您正在寻找的内容:

SELECT (firstname || ' ' || lastname) AS "FullName",
       StudentID AS "StudentID",
       Major1 as "DoubleDipping"
  FROM A5
  WHERE MAJOR1 = MAJOR2

如果你真的需要这个函数,返回结果集的常用方法是返回一个打开的SYS_REFCURSOR,然后调用者负责关闭。例如:

CREATE OR REPLACE FUNCTION DOUBLE_DIPPING_STUDENTS
    RETURN SYS_REFCURSOR
IS
  csr SYS_REFCURSOR;
BEGIN
  OPEN csr FOR SELECT (firstname || ' ' || lastname) AS "FullName",
                      StudentID AS "StudentID",
                      Major1 as "DoubleDipping"
                 FROM A5
                 WHERE MAJOR1 = MAJOR2;

  RETURN csr;
END DOUBLE_DIPPING_STUDENTS;

可以从PL/SQL块调用上述函数:

DECLARE
  csr       SYS_REFCURSOR;
  strNAME   VARCHAR2(2000);
  nID       A5.STUDENTID%TYPE;
  strMAJOR  A5.MAJOR1%TYPE;
BEGIN
  csr := DOUBLE_DIPPING_STUDENTS;

  LOOP
    FETCH csr
      INTO NAME, ID, MAJOR;

    WHEN csr%NOTFOUND THEN EXIT;

    DBMS_OUTPUT.PUT_LINE(strNAME || '  ' || nID || '  ' || strMAJOR);
  END LOOP;

  CLOSE csr;
END;