[英]Need to find the Max value in a SQL table and Based on the MAX value need to generate the Id's
[英]Need to find the max term_code value for each person in my table
我有一個具有多個 term_code 值的人員列表。 我需要找到每個擁有 201930 或 201940 記錄的人的最大值。 如果兩者都有,比如鮑勃的情況,我需要拿 201930。 然后,我需要為每個具有該術語的人返回其他字段。 只會返回紅色記錄。 Fred 不應該出現在 output 中。
這是我目前的查詢,但它獲取了 Bob 的 201940 記錄。 它的記錄總數是正確的,但它得到了一些不正確的值。
SELECT userid, term_code, race, gender
FROM mytable a JOIN (
SELECT userid, MAX(term_code) AS term_code
FROM mytable
WHERE term_code <= '201940'
GROUP BY userid
) b ON (a.userid = b.userid and a.term_code = b.term_code)
WHERE term_code IN ('201930', '201940');
使用這條線對我來說似乎是合乎邏輯的,它為 Bob 獲得了正確的值,但它使我的結果減少了大約 30%。
WHERE term_code <= COALESCE ('201930','201940')
有什么建議么?
NOT EXISTS
:
select m.* from mytable m
where m.term_code = (
case when not exists (select 1 from mytable where userid = m.userid and term_code = 201930)
then 201940
else 201930
end
)
或者,如果您只想要userid
和term_code
,那么您可以通過簡單的聚合來完成:
select userid, min(term_code) term_code
from mytable
where term_code in (201930, 201940)
group by userid
如果您想要表格中的整行,那么您可以加入表格:
select m.*
from mytable m inner join (
select userid, min(term_code) term_code
from mytable
where term_code in (201930, 201940)
group by userid
) t on t.userid = m.userid and t.term_code = m.term_code
或使用ROW_NUMBER()
window function:
select t.userid, t.term_code, t.race, t.gender
from (
select m.*,
row_number() over (partition by userid order by term_code) rn
from mytable m
where m.term_code in (201930, 201940)
) t
where t.rn = 1
見演示。
結果:
> USERID | TERM_CODE | RACE | GENDER
> :----- | --------: | :--- | :-----
> Bob | 201930 | null | null
> Tim | 201940 | null | null
with t (USERID, term_code ) as (
select 'Bob', 201601 from dual union all
select 'Bob', 201605 from dual union all
select 'Bob', 201609 from dual union all
select 'Bob', 202930 from dual union all
select 'Bob', 202940 from dual union all
select 'Bob', 202950 from dual union all
select 'Tom', 202940 from dual union all
select 'Tom', 201605 from dual union all
select 'Tom', 201609 from dual union all
select 'Mac', 201601 from dual union all
select 'Mac', 201605 from dual union all
select 'Mac', 201609 from dual
)
select userid, term_code from
(
SELECT t.*
, sum(case when term_code in (202930, 202940) then 1 end) over (partition by userid order by term_code) rnk
FROM t
)
where rnk = 1
USE TERM_CODE
--- ----------
Bob 202930
Tom 202940
請注意,除了您感興趣的值之外,term_code 值並不相同。對於每個 USERID,term_code 使用 SUM() 分析 function 根據您的條件進行排名。 一旦解決了這個問題,外部查詢就會簡單地過濾掉內部查詢中產生的排名第一的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.