表中的最小值

时间:2011-04-04 12:30:53

标签: mysql sql-server

我需要3 coloumn的最小值和min值的相应名称, 喜欢这个..

Name    val1   val2   val3
a       12       5       4
b       10       9       1
c       7        11      5
d       13       8       2

输出:

Name    MIN
b        1

我写了查询以找到最小值:

select MIN(less) 
from (
    select case 
        when val1<=val2 and val1<=val3 then val1
        when val2<=val1 and val2<=val3 then val2
        when val3<=val1 and val3<=val2 then val3 end as less from table) as low

我使用了alises,我想从表中显示相应的名称... plz告诉我查询......

2 个答案:

答案 0 :(得分:6)

您可以使用UNION运算符将3列表转换为包含1列的单个表。

SELECT  TOP 1 Name, Val AS Min
FROM (
    SELECT  Name, val1 AS Val
    FROM    table
    UNION
    SELECT  Name, val2 AS Val
    FROM    table
    UNION
    SELECT  Name, val3 AS Val
    FROM    table
) AS sub_query
ORDER BY Val ASC

此解决方案的另一个优点是,如果列数增加,则更容易维护。

答案 1 :(得分:5)

最简洁

SELECT top 1 Name,col,val 
FROM T 
UNPIVOT ( val for col in (val1,val2,val3)) unpvt
ORDER BY val

效率最高(假设这些列已编入索引)

;WITH cte(Name, col, val) AS
(
SELECT TOP 1 Name, 'val1', val1
FROM T 
ORDER BY val1
UNION ALL
SELECT TOP 1 Name, 'val2', val2  
FROM T 
ORDER BY val2
UNION ALL
SELECT TOP 1 Name, 'val3', val3  
FROM T 
ORDER BY val3
)
SELECT TOP 1 Name, col, val  
FROM cte 
ORDER BY val