如何通过 Oracle 中的 SQL 查询为每个 id 找到 TOP/MAX 值?
How find TOP/MAX value for each id via SQL query in Oracle?
如何使用查询查找每个标识符的最大值(不是唯一的)?
我的 table:
id date repeat_cycle
8 30.07.2020 0
4 28.04.2020 1
4 28.04.2020 0
15 01.01.2020 9
15 24.12.2019 8
15 23.12.2019 7
1 20.12.2019 5
15 19.12.2019 6
1 19.12.2019 4
我想要每个 id 的最大值(它在 repeat_cycle 中的最大数字)。
我的 SQL 查询是错误的,我不知道为什么。有人会建议如何修复它或其他查询。
SELECT * FROM (
SELECT
id,
date,
repeat_cycle
FROM table t1
order by repeat_cycle desc
) t1
and rownum=1;
您可以使用解析函数:
select *
from (
select
t.*,
row_number() over(partition by id order by repeat_cycle desc) rn
from mytable t
) t
where rn = 1
或者,如果 table 中只有三列,则 keep
语法可能是合适的:
select
id,
max(date) keep(dense_rank first order by repeat_cycle desc) date,
max(repeat_cycle) repeat_cycle
from mytable
您可以使用 max()
和 group by
。
select
t.id,
max(t.repeat_cycle)
from
table t
group by
t.id
其中 table 是您的真实 table 姓名。
您可以使用row_number()
,
select id, date, repeat_cycle from
(select id, date, repeat_cycle, row_number() over(partition by id order by repeat_cycle desc) as rnk from table_name)
qry where rnk = 1;
我建议您不要使用诸如“日期”之类的关键字或您的 table 之类的关键字来调用您的列,例如“table”
select t1.id, t1.date_c, t1.repeat_cycle
from table_t t1
where (t1.id, t1.repeat_cycle) in (select t2.id, max(t2.repeat_cycle)
from table_t t2
group by t2.id);
如何使用查询查找每个标识符的最大值(不是唯一的)? 我的 table:
id date repeat_cycle
8 30.07.2020 0
4 28.04.2020 1
4 28.04.2020 0
15 01.01.2020 9
15 24.12.2019 8
15 23.12.2019 7
1 20.12.2019 5
15 19.12.2019 6
1 19.12.2019 4
我想要每个 id 的最大值(它在 repeat_cycle 中的最大数字)。 我的 SQL 查询是错误的,我不知道为什么。有人会建议如何修复它或其他查询。
SELECT * FROM (
SELECT
id,
date,
repeat_cycle
FROM table t1
order by repeat_cycle desc
) t1
and rownum=1;
您可以使用解析函数:
select *
from (
select
t.*,
row_number() over(partition by id order by repeat_cycle desc) rn
from mytable t
) t
where rn = 1
或者,如果 table 中只有三列,则 keep
语法可能是合适的:
select
id,
max(date) keep(dense_rank first order by repeat_cycle desc) date,
max(repeat_cycle) repeat_cycle
from mytable
您可以使用 max()
和 group by
。
select
t.id,
max(t.repeat_cycle)
from
table t
group by
t.id
其中 table 是您的真实 table 姓名。
您可以使用row_number()
,
select id, date, repeat_cycle from
(select id, date, repeat_cycle, row_number() over(partition by id order by repeat_cycle desc) as rnk from table_name)
qry where rnk = 1;
我建议您不要使用诸如“日期”之类的关键字或您的 table 之类的关键字来调用您的列,例如“table”
select t1.id, t1.date_c, t1.repeat_cycle
from table_t t1
where (t1.id, t1.repeat_cycle) in (select t2.id, max(t2.repeat_cycle)
from table_t t2
group by t2.id);