如何从列中获取最小值

时间:2013-09-09 06:40:09

标签: sql sql-server-2008 sql-server-2005

我有一个表项目,我想获得特定ID的项目的最低价格

表项:

Id    Price1                Price2           Price3
1       10                    20                30
2       20                    30                40

根据上面的示例, id-1 的最低价格 10 id-2 的最低价格 20 < / strong>即可。我只是想从三列中获取特定id的最小值。

请记住:我无法创建案例,因为任何列都可以为null。提前谢谢。

5 个答案:

答案 0 :(得分:2)

一种方法可能是这样的:

SELECT Id, MIN(Price) FROM (
   SELECT Id, Price1 As Price FROM Table1
   UNION ALL
   SELECT Id, Price2 As Price FROM Table1
   UNION ALL
   SELECT Id, Price3 As Price FROM Table1
) As AllValues
GROUP BY Id

即使有null个值,也会有效。这是working demo

答案 1 :(得分:1)

两个类似的解决方案,使用 APPLY 运算符:

SELECT t.Id,
       MIN(m.Price)
FROM   
    tableX AS t
  CROSS APPLY
    ( SELECT Price = Price1 UNION
      SELECT Price2 UNION
      SELECT Price3 
    ) AS m
GROUP BY t.Id ;



SELECT t.Id,
       x.Price
FROM   
    tableX AS t
  OUTER APPLY
    ( SELECT TOP (1) Price
      FROM 
       ( SELECT Price1 UNION
         SELECT Price2 UNION  
         SELECT Price3
       ) AS m (Price)
       WHERE Price IS NOT NULL
       ORDER BY Price ASC
    ) x ;

SQL-Fiddle

进行测试

答案 2 :(得分:0)

请尝试:

Select Id,
       Case When Price1 < Price2 And Price1 < Price3 Then Price1
            When Price2 < Price1 And Price2 < Price3 Then Price2 
            Else Price3
            End As TheMin
From   
    YourTable

OR

select 
    Id, 
    MIN(Price) TheMin
FROM
(
    select Id, Price1 Price From YourTable
    union all
    select Id, Price2 Price From YourTable
    union all
    select Id, Price3 Price From YourTable
)x group by Id

答案 3 :(得分:0)

获取NULL的最大值:

Select Id,
       Case When ISNULL(Price1,MaxPrice) < ISNULL(Price2,MaxPrice)  And ISNULL(Price1,MaxPrice)  < ISNULL(Price3,MaxPrice)  Then ISNULL(Price1,MaxPrice)
            When ISNULL(Price2,MaxPrice)  < ISNULL(Price1,MaxPrice)  And ISNULL(Price2,MaxPrice)  < ISNULL(Price3,MaxPrice)  Then ISNULL(Price2,MaxPrice)  
            Else ISNULL(Price3,MaxPrice) 
            End As TheMin
From   
    YourTable

可以计算MaxPrice或只计算max int ...

答案 4 :(得分:0)

看一下这篇文章。我的意思是你可以反转表格列&amp;行,只需使用min()即可获得最小值。

Select MYSQL rows but rows into columns and column into rows

(链接帖子中Anax的所有功劳)