微软SQL
表看起来像这样
ID 1 | 2 | 3 | 4 | 5
AA1 1 | 1 | 1 | 2 | 1
关于如何进行查询以返回的任何线索
ID | MaxNo
AA1 | 4
,使用上表示例?我知道我可以写一个 case blah when 声明,但我觉得有一种更简单的方法来做到这一点
微软SQL
表看起来像这样
ID 1 | 2 | 3 | 4 | 5
AA1 1 | 1 | 1 | 2 | 1
关于如何进行查询以返回的任何线索
ID | MaxNo
AA1 | 4
,使用上表示例?我知道我可以写一个 case blah when 声明,但我觉得有一种更简单的方法来做到这一点
您可以使用UNPIVOT
将这些可比较的项目正确地1放入同一列,然后用于ROW_NUMBER()
查找最高值的行2:
declare @t table (ID char(3) not null,[1] int not null,[2] int not null,
[3] int not null,[4] int not null,[5] int not null)
insert into @t (ID,[1],[2],[3],[4],[5]) values
('AA1',1,1,1,2,1)
;With Unpivoted as (
select *,ROW_NUMBER() OVER (ORDER BY Value desc) rn
from @t t UNPIVOT (Value FOR Col in ([1],[2],[3],[4],[5])) u
)
select * from Unpivoted where rn = 1
结果:
ID Value Col rn
---- ----------- ------------------------- --------------------
AA1 2 4 1
1如果您有来自同一个“域”的数据出现在同一个表的多个列中(这样比较这些值甚至是有意义的),这通常是属性分裂的迹象,您的部分数据被错误地用于构成列名的一部分。
2在您的问题中,您说“每行”,但您只给出了一行样本。如果我们假设ID
每行的值都是唯一的,并且您想分别找到每个 的最大值ID
,那么您将编写ROW_NUMBER()
asROW_NUMBER() OVER (PARTITION BY ID ORDER BY Value desc) rn
来获得(我希望)您正在寻找的结果。
您可以在max()
对一行的列进行操作的地方使用交叉应用。
select T1.ID,
T2.Value
from YourTable as T1
cross apply
(
select max(T.Value) as Value
from (values (T1.[1]),
(T1.[2]),
(T1.[3]),
(T1.[4]),
(T1.[5])) as T(Value)
) as T2
如果您使用的是 SQL Server 2005,则可以union all
在派生表中使用values()
.
select T1.ID,
T2.Value
from YourTable as T1
cross apply
(
select max(T.Value) as Value
from (select T1.[1] union all
select T1.[2] union all
select T1.[3] union all
select T1.[4] union all
select T1.[5]) as T(Value)
) as T2