0

我是一个需要一些建议的 SQL 新手。执行以下操作的最有效(运行最快的查询)方法是什么 -

之后从表中选择所有列 -

- 根据两列中包含的唯一值执行“分组依据”:“top_line_id”和“external_reference”。

- 根据包含在不同字段(例如 support_id)中的最大值或最小值(不管是哪一个)从每个组中选择一条记录。

我团队中的某个人提供了以下查询,但我似乎无法使其正常工作。当我尝试执行它时,我收到一条错误消息,指出“无效的关系运算符”。

Select * 
from STAGE.SFS_GH_R3_IB_ENTLMNT_CONTACTS
Where support_id, external_reference, top_line_id in (
         select max(support_id), 
                external_reference, 
                top_line_id from STAGE.SFS_GH_R3_IB_ENTLMNT_CONTACTS
)

还有一件事 - 我们正在执行 Group By 的列在某些记录中包含空值。我们希望那些从查询中排除的人。

非常感谢您提供的任何帮助。

4

2 回答 2

2

尽管您将其表述为按查询分组,但还有另一种方法使用 row_number()。这将根据“order by”子句枚举组中的每一行。在以下查询中,它根据 external_reference 和 top_line_id 枚举每个组,按 support_id 排序:

select *
from (Select t.*,
             row_number() over (partition by external_reference, top_line_id
                                order by support_id) as seqnum
      from STAGE.SFS_GH_R3_IB_ENTLMNT_CONTACTS t
     )
where seqnum = 1
于 2012-05-20T04:46:28.387 回答
0

这应该有效(无法测试)


SELECT
  *
FROM
  stage.sfs_gh_r3_ib_entlmnt_contacts
WHERE
  (support_id, external_reference, top_line_id) IN
    (
      SELECT
        max(support_id), 
        external_reference, 
        top_line_id
      FROM
        stage.sfs_gh_r3_ib_entlmnt_contacts
      WHERE
        external_reference IS NOT NULL AND
        top_line_id IS NOT NULL
      GROUP BY
        top_line_id, external_reference
    )
于 2012-05-20T04:49:43.487 回答