[英]Return column name of max value in a row SQL Server
Initial Table:初始表:
Name Job1 Job2 Job3 Job4 Job5 Job6
--------------------------------------------------------------
A 34 0 66 0 0 0
B 33 33 33 1 0 0
C 100 0 0 0 0 0
D 50 0 0 0 0 50
Output Table: Output 表:
Name Max Job1 Job2 Job3 Job4 Job5 Job6
----------------------------------------------------------------------------
A Job3 34 0 66 0 0 0
B Job1;Job2;Job3 33 33 33 1 0 0
C Job1 100 0 0 0 0 0
D Job1;Job6 50 0 0 0 0 50
I need to get the Job Name (column name) of the row with the max value in SQL Server.我需要在 SQL 服务器中获取具有最大值的行的作业名称(列名)。 Is there a way other than else if to do this because 'greatest' function is not available in SQL?
如果这样做,是否有其他方法,因为 SQL 中没有“最大的”function? (Coz I have 50 Jobs at least)
(因为我至少有 50 个工作)
You can use apply
and window functions:您可以使用
apply
和 window 函数:
select t.*, max_cols
from t cross apply
(select string_agg(colname, ';') as max_cols
from (select top (1) with ties v.colname
from (values ('Job1', t.job1), ('Job2', t.job2), . . .
) v(colname, job)
order by v.job desc
) v
) v;
That said, you should probably fix your data model.也就是说,您可能应该修复您的数据 model。 Having multiple columns with the same information is usually a sign of a deficient data model.
具有相同信息的多个列通常表示数据不足 model。 Each
name
/ job
combination should be a separate row in another table.每个
name
/ job
组合应该是另一个表中的单独行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.