select max(some_column1), some_column2 from(
select distinct some_column1, some_column2 from table1 where some_column1 = (select max(some_column1) from table1)
union all
select distinct some_column1, some_column2 from table2 where some_column1 = (select max(some_column1) from table2)
union all
select distinct some_column1, some_column2 from table3 where some_column1 = (select max(some_column1) from table3)
) as max_result
此查询完全符合我的要求。唯一的问题是,当我从some_column1获得最大结果时,我还想获得与max(some_column1)相对应的some_column2。相反,我得到了3个结果。我需要将其限制为一个结果。 some_column2必须与max(some_column1)在同一个表中。除了将结果存储到临时表中之外,还有这样做吗? 所有帮助表示赞赏。提前谢谢!
答案 0 :(得分:1)
给它一个镜头..它有点复杂......但应该工作..如果最大值有一个平局,并且你想要所有的那么,那么只需替换=
检查where子句与IN
select max_result.some_column1,max_result.some_column2 from (
select distinct some_column1, some_column2 from table1 where some_column1 = (select max(some_column1) from table1)
union all
select distinct some_column1, some_column2 from table2 where some_column1 = (select max(some_column1) from table2)
union all
select distinct some_column1, some_column2 from table3 where some_column1 = (select max(some_column1) from table3)
) max_result
where max_result.some_column1 =
(select max(some_column1) from
(
select distinct some_column1, some_column2 from table1 where some_column1 = (select max(some_column1) from table1)
union all
select distinct some_column1, some_column2 from table2 where some_column1 = (select max(some_column1) from table2)
union all
select distinct some_column1, some_column2 from table3 where some_column1 = (select max(some_column1) from table3)
))
答案 1 :(得分:1)
我认为最简单的方法是按some_column1排序并取第一行。这将获得some_column1具有更大值的行,并且仍然可以访问some_column2。
尝试:
select top 1 some_column1, some_column2 from(
select distinct some_column1, some_column2 from @table1 where some_column1 = (select max(some_column1) from @table1)
union all
select distinct some_column1, some_column2 from @table2 where some_column1 = (select max(some_column1) from @table2)
union all
select distinct some_column1, some_column2 from @table3 where some_column1 = (select max(some_column1) from @table3)
) as max_result
order by some_column1 desc