2016-04-27 22 views
0
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)相同的表。無論如何,除了將結果存儲到臨時表中之外,還需要執行此操作嗎? 所有幫助表示讚賞。提前致謝!如何選擇多列,其中一列是來自多個表的max()

回答

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 
1

給這shot..Its一個有點令人費解......但應該work..If存在最大值領帶,並希望所有的話,那麼就用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) 
))