MySQL-查找非零的最小值

时间:2018-11-03 14:38:29

标签: mysql

样品表

----------------------------------------
Fruit           Store1           Store2
Apple             5                 6
Banana            10                4
Oranges           1                 1
Avocado           2                 1
----------------------------------------

显然,SELECT MIN(NULLIF(Store1, 0)) FROM table仅获取值,而不获取包含它的行。我还需要在两个商店之间进行比较并获取商店名称。

这是每个项目队列的目标输出

----------------------------
Fruit      Lowest     Source
Apple        5        Store1
----------------------------

----------------------------
Fruit      Lowest     Source
Banana       4        Store2
----------------------------

----------------------------
Fruit      Lowest     Source
Oranges      1        Store1
----------------------------

----------------------------
Fruit      Lowest     Source
Avocado      1        Store2
----------------------------

1 个答案:

答案 0 :(得分:0)

理想情况下,您应该考虑规范化表结构。如果您打算在表中增加商店,则为每个商店添加新列将使一切繁琐。

相反,您只有三列,即 viz fruitstore_noquantity。还有更多的可能性,例如分别为fruitstore使用单独的主表。以简单的形式,您可以考虑以下内容:

Create Table fruits (fruit varchar(32), 
                     store_no varchar(16), 
                     quantity int);
Insert Into fruits 
Values 
('Apple', 'Store1', 5), 
('Apple', 'Store2', 6), 
('Banana', 'Store1', 10), 
('Banana', 'Store2', 4), 
('Oranges', 'Store1', 1), 
('Oranges', 'Store2', 1), 
('Avocado', 'Store1', 2), 
('Avocado', 'Store2', 1);

查询#1

SELECT * FROM fruits;

| fruit   | store_no | quantity |
| ------- | -------- | -------- |
| Apple   | Store1   | 5        |
| Apple   | Store2   | 6        |
| Banana  | Store1   | 10       |
| Banana  | Store2   | 4        |
| Oranges | Store1   | 1        |
| Oranges | Store2   | 1        |
| Avocado | Store1   | 2        |
| Avocado | Store2   | 1        |

查询2(以获取所需的输出格式)

SELECT 
  f.fruit, 
  MIN(f.quantity) AS lowest, 
  MIN(f.store_no) AS `source`
FROM fruits AS f 
JOIN 
( SELECT fruit, 
         MIN(quantity) AS lowest 
  FROM fruits 
  WHERE quantity > 0 
  GROUP BY fruit 
) AS dt ON dt.fruit = f.fruit AND 
           dt.lowest = f.quantity 
GROUP BY f.fruit;

| fruit   | lowest | source |
| ------- | ------ | ------ |
| Apple   | 5      | Store1 |
| Avocado | 1      | Store2 |
| Banana  | 4      | Store2 |
| Oranges | 1      | Store1 |

View on DB Fiddle


上一个解决方案: 在现有结构的情况下,只有两列 viz Store1Store2,您可以使用条件比较函数,例如Case .. When

请始终记住,Min()函数用于从列的不同值中查找最小值。在这里,您尝试从多个列中查找最小值。

SELECT 
  Fruit, 
  (
   CASE WHEN Store1 < Store2 AND Store1 > 0 THEN Store1
        ELSE Store2 
   END
  ) AS Lowest, 
  (
   CASE WHEN Store1 < Store2 AND Store1 > 0 THEN 'Store1'
        WHEN Store2 > 0 THEN 'Store2' 
        ELSE 'N/A' 
   END
  ) AS Source
FROM your_table