根据列之间的比较将最大值的列名称指定给行

时间:2013-10-14 18:48:19

标签: sql sql-server sql-server-2012

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

考虑某个地区的医院就诊表(OID)。我想做的是在sql中自动确定上表中的最后两列。我想比较每个区域(A,B,C)的所有医院就诊(HOS1,HOS2,HOS3),并为每个区域分配MAXV列的最高访问次数和访问次数最多的医院代码到MAXH列,看起来像下表。

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

2 个答案:

答案 0 :(得分:3)

对于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这是一个演示。 以下是结果:

╔═════╦══════╦══════╦══════╦══════╦══════╗
║ OID ║ HOS1 ║ HOS2 ║ HOS3 ║ MAXV ║ MAXH ║
╠═════╬══════╬══════╬══════╬══════╬══════╣
║ A   ║    3 ║    7 ║   10 ║   10 ║ HOS3 ║
║ B   ║   12 ║    5 ║    8 ║   12 ║ HOS1 ║
║ C   ║    3 ║   13 ║    7 ║   13 ║ HOS2 ║
╚═════╩══════╩══════╩══════╩══════╩══════╝

答案 1 :(得分:2)

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