3

我有一个比这里的示例更复杂的查询,但它只需要返回某个字段在数据集中不多次出现的行。

ACTIVITY_SK      STUDY_ACTIVITY_SK
100              200
101              201
102              200
100              203

在此示例中,我不希望ACTIVITY_SK返回任何值为 100 的记录,因为ACTIVITY_SK它在数据集中出现了两次。

数据是一个映射表,用于许多连接,但是像这样的多条记录意味着数据质量问题,所以我需要简单地将它们从结果中删除,而不是在其他地方造成错误连接。

SELECT 
   A.ACTIVITY_SK,
   A.STATUS,
   B.STUDY_ACTIVITY_SK,
   B.NAME,
   B.PROJECT
 FROM
   ACTIVITY A,
   PROJECT B
 WHERE 
   A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK

我曾尝试过这样的事情:

SELECT 
   A.ACTIVITY_SK,
   A.STATUS,
   B.STUDY_ACTIVITY_SK,
   B.NAME,
   B.PROJECT
 FROM
   ACTIVITY A,
   PROJECT B
 WHERE 
   A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK
 WHERE A.ACTIVITY_SK NOT IN
 (

  SELECT 
     A.ACTIVITY_SK,
     COUNT(*)
    FROM
      ACTIVITY A,
      PROJECT B
    WHERE 
    A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK
    GROUP BY A.ACTIVITY_SK
    HAVING COUNT(*) > 1

 )

但是必须有一种更便宜的方法来做到这一点......

4

2 回答 2

5

像这样的东西运行起来可能有点“便宜”:

SELECT
   A.ACTIVITY_SK,
   A.STATUS,
   B.STUDY_ACTIVITY_SK,
   B.NAME,
   B.PROJECT
PROJECT B INNER JOIN
   (SELECT 
       ACTIVITY_SK,
       MIN(STATUS) STATUS,
    FROM
      ACTIVITY
    GROUP BY ACTIVITY_SK
    HAVING COUNT(ACTIVITY_SK) = 1 ) A
ON A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK
于 2012-02-01T21:07:56.410 回答
1

另一种选择:

select * from (
  SELECT 
     A.ACTIVITY_SK,
     A.STATUS,
     B.STUDY_ACTIVITY_SK,
     B.NAME,
     B.PROJECT,
     count(distinct a.pk) over (partition by a.activity_sk) AS c
   FROM
     ACTIVITY A,
     PROJECT B
   WHERE 
     A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK
) where c = 1;

(其中a.pk指的是 ACTIVITY 表中的唯一标识符)

于 2012-02-02T05:24:33.137 回答