在 SQL 查询中获取 oracle 中除 1 以外的其他排名值
getting other rank value than 1 in oracle in SQL query
当我像下面这样使用时,有 1 个 SQL 查询-
select * from
(select a.id, a.nm, b.pd, b.date, rank() over(partition by a.id order by b.date desc) rnk
from tab1 a, tab2 b where a.id = b.id)
where rnk =1
然后得到如下输出-
id nm pd date rnk
-- --- --- ---------- ---
11 abc a15 11/04/2022 1
11 abc a15 11/04/2022 1
14 gef a23 11/04/2022 1
14 gef a23 10/04/2022 12
19 lfb a37 11/04/2022 1
19 lfb a37 08/04/2022 21
但我只希望一个值按最新日期排序为 select。您能否帮我解决这个问题,将其解决为 select 1 个 id 的一个值,如下所示-
id nm pd date rnk
-- --- --- ---------- ---
11 abc a15 11/04/2022 1
14 gef a23 11/04/2022 1
19 lfb a37 11/04/2022 1
您需要在 RANK()
的排序依据中指定第二列,这样就不会有重复的值对。
例如b.id
我还规范化了 JOIN。
select * from
(select
a.id,
a.nm,
b.pd,
b.date,
rank() over (
partition by a.id
order by b.[date] desc, b.id asc
) as rnk
from tab1 a
join tab2 b on a.id = b.id
) s
where rnk = 1;
你有没有这样试过,因为有时 rank()
函数在 main SQL 之外不起作用。试一试,希望能成功。
SELECT id,
nm,
pd, date
FROM
(SELECT *
FROM
(SELECT a.id,
a.nm,
b.pd,
b.date ,
rank() over(PARTITION BY a.id
ORDER BY b.date DESC) rnk
FROM tab1 a,
tab2 b
WHERE a.id = b.id))
WHERE rnk =1
当我像下面这样使用时,有 1 个 SQL 查询-
select * from
(select a.id, a.nm, b.pd, b.date, rank() over(partition by a.id order by b.date desc) rnk
from tab1 a, tab2 b where a.id = b.id)
where rnk =1
然后得到如下输出-
id nm pd date rnk
-- --- --- ---------- ---
11 abc a15 11/04/2022 1
11 abc a15 11/04/2022 1
14 gef a23 11/04/2022 1
14 gef a23 10/04/2022 12
19 lfb a37 11/04/2022 1
19 lfb a37 08/04/2022 21
但我只希望一个值按最新日期排序为 select。您能否帮我解决这个问题,将其解决为 select 1 个 id 的一个值,如下所示-
id nm pd date rnk
-- --- --- ---------- ---
11 abc a15 11/04/2022 1
14 gef a23 11/04/2022 1
19 lfb a37 11/04/2022 1
您需要在 RANK()
的排序依据中指定第二列,这样就不会有重复的值对。
例如b.id
我还规范化了 JOIN。
select * from
(select
a.id,
a.nm,
b.pd,
b.date,
rank() over (
partition by a.id
order by b.[date] desc, b.id asc
) as rnk
from tab1 a
join tab2 b on a.id = b.id
) s
where rnk = 1;
你有没有这样试过,因为有时 rank()
函数在 main SQL 之外不起作用。试一试,希望能成功。
SELECT id,
nm,
pd, date
FROM
(SELECT *
FROM
(SELECT a.id,
a.nm,
b.pd,
b.date ,
rank() over(PARTITION BY a.id
ORDER BY b.date DESC) rnk
FROM tab1 a,
tab2 b
WHERE a.id = b.id))
WHERE rnk =1