如何 select 多列,其中一列是多个表中的 max()

How to select multiple column with one column being max() from multiple tables

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) 相同的 table。除了将结果存储到临时 table 之外,还有什么办法可以做到这一点吗? 感谢所有帮助。提前致谢!

试一试..它有点令人费解...但应该可以..如果最大值相同,并且您想要全部,那么只需替换 = 签入带有 IN

的 where 子句
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)
))

我认为最简单的方法是按 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