2

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

表项:

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

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

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

4

5 回答 5

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值,这也有效。这是工作演示

于 2013-09-09T06:47:38.513 回答
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测试

于 2013-09-09T06:51:49.650 回答
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

或者

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
于 2013-09-09T06:43:33.760 回答
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...

于 2013-09-09T06:46:37.740 回答
0

看看这篇文章。我的想法是您可以反转表格的列和行并简单地使用 min() 来获得最小值。

选择 MYSQL 行,但将行选择为列,将列选择为行

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

于 2013-09-09T06:51:10.787 回答