output the column name with the highest value

你离开我真会死。 提交于 2019-12-13 02:55:24

问题


I have a lot of columns with numbers in them in a SQL Server table. I need to check the specific columns for the highest number and output the name of the column for each row in the table.

For example:

RED | BLUE | GREEN | BLACK | Highest Column

0      2       1       4         BLACK <-- Outputted result of an expression

I have a dataset that pulls all the columns from the database table. I need an expression that will evaluate the data and return the highest valued column name.

I'm not sure of the logic behind this type of situation. Any help would be appreciated.

This is an SSRS report.


回答1:


Use CROSS APPLY. This will give you the highest valued color(black):

DECLARE @t table(red int, blue int, green int, black int)-- | Highest Column
INSERT @t values(0,2,1,4)

SELECT red, blue, green, black, highest 
FROM @t -- replace @t with your own table
CROSS APPLY
(SELECT top 1 color highest
FROM
  (VALUES('RED', red), ('BLUE', blue), 
  ('GREEN', green), ('BLACK', black)) x(color, value)
ORDER BY value desc) x

It should be quite easy to replace @t with your own table.



来源:https://stackoverflow.com/questions/30598895/output-the-column-name-with-the-highest-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!