筛选表格以获取唯一的ID,无需子查询。

huangapple go评论61阅读模式
英文:

Filter table to unique IDs without subquery

问题

I can help you translate the code portion without the need for subqueries, CTEs, or views:

select sorhsch.*
from sorhsch
inner join (
    select sorhsch_pidm as pidm,
           max(sorhsch_surrogate_id) as good_row
    from sorhsch 
    group by sorhsch_pidm) sorhsch_filter
on sorhsch_pidm = pidm
and sorhsch_surrogate_id = good_row;

Here's the translated code:

选择 sorhsch.* -- 选择任意表
 sorhsch
内部连接 (
    选择 sorhsch_pidm 作为 pidm,
           max(sorhsch_surrogate_id) 作为 good_row
     sorhsch 
    分组按 sorhsch_pidm) sorhsch_filter
 sorhsch_pidm = pidm
 sorhsch_surrogate_id = good_row;

Please note that this translation only includes the code portion, as you requested.

英文:

I've got a table that looks something like this:

User ID (sorhsch_pidm) High school (sorhsch_sbgi_code) Surrogate ID (sorhsch_surrogate_id)
123 blah HS 1
123 blah2 HS 2
234 blah HS 3
345 blah4 HS 4
567 homeschool 5

Contextually, I'd expect this particular table's schema to enforce uniqueness on the sorhsch_pidm field. (according to my vendor, the surrogate_id field is just a row number.) The problem is that it doesn't. I'm not sure why, but what I know is that I need to reduce it down until no sorhsch_pidm has >1 row. I don't really care which row gets chosen, only that exactly one remains for later querying.

Of course, I can do something like:

select sorhsch.* --IE select arbitrary tables
from sorhsch
inner join (
    select sorhsch_pidm as pidm,
           max(sorhsch_surrogate_id) as good_row
    from sorhsch 
    group by sorhsch_pidm) sorhsch_filter
on sorhsch_pidm = pidm
and sorhsch_surrogate_id = good_row;

but this solution has me defining a subquery, which I personally dislike. Is there a way of solving this problem without using subqueries, CTEs, or views?

答案1

得分: 2

你可以使用带有WITH TIES选项的行限制子句,如下所示:

select * from sorhsch
order by row_number() over (partition by sorhsch_pidm order by sorhsch_surrogate_id desc)
fetch next 1 row with ties

demo

英文:

You can use the row limiting clause with the WITH TIES option as the following:

select * from sorhsch
order by row_number() over (partition by sorhsch_pidm order by sorhsch_surrogate_id desc)
fetch next 1 row with ties

demo

huangapple
  • 本文由 发表于 2023年5月18日 12:02:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定