2016-04-27 20 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つの結果を得る。私は1つの結果にそれを制限する必要があります。 some_column2はmax(some_column1)と同じテーブルからのものでなければなりません。結果をテンポラリテーブルに格納するだけでなく、これを行うにはどうしたらいいですか? すべての助力に感謝します。前もって感謝します!複数のテーブルから1つの列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

ビット入り組んこのs​​hot..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) 
))