如何使用WHERE子句提取最大值和最小值?

时间:2019-05-10 09:50:19

标签: sql

我编写了一个脚本来提取列(trail_seq_no)中的最小值和最大值。但是,我不知道该列中的最大值。假设我要提取表中的所有列(使用select *),如何提取该列中的最大值?

我不能使用select max(trail_seq_no),因为我想要表中的所有列。

select * from a_site_id a 
left join facility_trail_items_temp ft1 on ft1.a_site_id = a.a_site_id                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
left JOIN FACILITY_TRAIL_ITEMS_TEMP ft2 on ft2.parent_fac_trl_itm_id = ft1.parent_fac_trl_itm_id 
where ft2.resource_reference like 'ZG%' and ft2.trail_seq_no = 1.0;

2 个答案:

答案 0 :(得分:0)

在where条件中使用子查询

 select a.*  
    from a_site_id a 
    left join facility_trail_items_temp ft1 on ft1.a_site_id = a.a_site_id                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    _temp ft on ft.a_site_id = a.a_site_id
    left JOIN FACILITY_TRAIL_ITEMS_TEMP ft2 on ft2.parent_fac_trl_itm_id = ft1.parent_fac_trl_itm_id 
where 
ft2.resource_reference like 'ZG%' and
    (ft2.trail_seq_no = 1.0 or 
    ft2.trail_Seq_no = (select max(trail_seq_no) from  FACILITY_TRAIL_ITEMS_TEMP)
    )

答案 1 :(得分:0)

您可以使用order by并将其限制为一行:

select *
from a_site_id a left join 
     facility_trail_items_temp ft1
     on ft1.a_site_id = a.a_site_id left JOIN 
     FACILITY_TRAIL_ITEMS_TEMP ft2
     on ft2.parent_fac_trl_itm_id = ft1.parent_fac_trl_itm_id 
where ft2.resource_reference like 'ZG%'
order by ft2.trail_seq_no desc
fetch first 1 row only;