如何通过使用"Case"语句比较多个列的值来检索具有最大值的列名



如何使用"Case"语句比较多个列的值来检索具有最大值的列名

例如:有超过 10 列。

A B C D E       Result  
1 2 3 1 5        E

E 列具有最高的 no,在结果列中,我应该得到"E"作为答案。

这里 A B C D E 结果是列 ..通过比较来自 A,B,C,D,E 的值,我应该使用 Case 表达式获取结果列中最大 no 的列名。

SQL的大多数方言都支持greatest()least()

select greatest(a, b, c, d, e) as greatest,
least(a, b, c, d, e) as least

那些通常没有其他机制的人。 例如,SQLite重载min()max()

select min(a, b, c, d, e) as greatest,
max(a, b, c, d, e) as least

或者,在SQL Server中,我会使用apply

select v.*
from t cross apply
(select max(val) as greatest, min(val) as least
from (values (a), (b), (c), (d), (e)) v(val)
) v;

用 CASE?也许是这样的东西?

SQL> with test (a, b, c, d) as
2    (select 1, 2, 3, 1 from dual)
3  select
4    case when a >= b and a >= c and a >= d then a
5         when b >= a and b >= c and b >= d then b
6         when c >= a and c >= b and c >= d then c
7         when d >= a and d >= b and d >= c then d
8    end result
9  from test;
RESULT
----------
3
SQL>

不敢相信...典型的设计问题。很多令人头疼的问题来自于数据库设计人员根本不应该接触数据库的事实。

您希望从不同的列中获取最大值:这意味着这些列中的数据具有相同的上下文。我们在这里比较苹果,橙子,桃子和香蕉!

由于您正在比较具有相同上下文的数据,因此它们应该都位于同一列中。使试图帮助您避免挠脑筋的人。噗嗤...

我的解决方案有点野蛮...

create table jeez(
jeez_id serial primary key,
row_id integer,
row_value integer)

insert into jeez (row_id, row_value)
select TheTableWithNoName_id, column_a from TheTableWithNoName
union
select TheTableWithNoName_id, column_b from TheTableWithNoName
union
select TheTableWithNoName_id, column_c from TheTableWithNoName
union
select TheTableWithNoName_id, column_d from TheTableWithNoName

所以现在你可以做:

select row_id, max(row_value)
from jeez
group by 1
order by 1

难以置信。

最新更新