简体   繁体   中英

Assign column name of max value to row based on comparison across columns

OID_ _ HOS1 _ _ HOS2 _ _ HOS3   
 A _ _ _ _ 3 _ _ _ _ _7 _ _ _ _10  
 B _ _ _ _ 12 _ _ _ _ 5 _ _ _ _ 8   
 C _ _ _ _ 3 _ _ _ _ 13_ _ _ _ 7  

Consider this table of hospital visit in a given region (OID). What I would like to do is in sql automatically determine the last two columns of the table above. I want to compare all of the hospitals visits (HOS1, HOS2, HOS3) for each region (A, B, C) and for each region assign the highest number of visits to a MAXV column and the code of the hospital with the highest visits to a column MAXH so that it looks like the table below.

OID_ _ HOS1 _ _ HOS2 _ _ HOS3 _ _ MAXV _ _ MAXH  
 A _ _ _ _ 3 _ _ _ _ _ 7_ _ _ _ _ 10 _ _ _ 10 _ _ _ HOS3  
 B _ _ _ _ 12 _ _ _ _ 5 _ _ _ _ _ 8 _ _ _ _12 _ _ _ HOS1  
 C _ _ _ _ 3 _ _ _ _ 13 _ _ _ _ _ 7 _ _ _ _13 _ _ _ HOS2

For SQL Server 2005+:

SELECT T.*, C.ColValue MAXV, C.ColName MAXH
FROM YourTable T
OUTER APPLY (SELECT TOP 1 *
             FROM (SELECT 'HOS1', HOS1
                   UNION ALL
                   SELECT 'HOS2', HOS2
                   UNION ALL
                   SELECT 'HOS3', HOS3) X(ColName,ColValue)
             ORDER BY ColValue DESC) C

Here is a demo of this. And here are the results:

╔═════╦══════╦══════╦══════╦══════╦══════╗
║ OID ║ HOS1 ║ HOS2 ║ HOS3 ║ MAXV ║ MAXH ║
╠═════╬══════╬══════╬══════╬══════╬══════╣
║ A   ║    3 ║    7 ║   10 ║   10 ║ HOS3 ║
║ B   ║   12 ║    5 ║    8 ║   12 ║ HOS1 ║
║ C   ║    3 ║   13 ║    7 ║   13 ║ HOS2 ║
╚═════╩══════╩══════╩══════╩══════╩══════╝
select
    t.[OID], t.[HOS1], t.[HOS2], t.[HOS3],
    c.MAXV, c.MAXH
from Table1 as t
    outer apply (
        select top 1 *
        from (values
           (HOS1, 'HOS1'),
           (HOS2, 'HOS2'),
           (HOS3, 'HOS3')
        ) as a(MAXV, MAXH)
        order by a.MAXH desc
    ) as C

sql fiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM