简体   繁体   English

从SQL中的同一行返回最小值的列名称

[英]Return Column name for Minimum value from the Same Row in SQL

I want to retrieve the minimum value and the corresponding column name from table with the same row. 我想从具有相同行的表中检索最小值和对应的列名。 See the query for retrieving the minimum value: 请参阅查询以获取最小值:

SELECT least(supplier1,supplier2,supplier3,supplier4,supplier5) AS minValue 
FROM 
priceTable  
WHERE partno='OL0003';

The above produces 20. Now, i want to pick the 20 and the column name which is Supplier1 in this case. 上面产生20。现在,我想选择20和在这种情况下为Supplier1的列名称。 What query do i need to add or is there a refactor code that can help do this at once. 我需要添加什么查询,或者有重构代码可以立即帮助您完成此操作。 I am using mysql 我正在使用mysql 在此处输入图片说明

After that, you need a case expression: 之后,您需要一个case表达式:

SELECT least(supplier1, supplier2, supplier3, supplier4, supplier5) AS minValue,
        (CASE least(supplier1, supplier2, supplier3, supplier4, supplier5)
              WHEN supplier1 THEN 'supplier1'
              WHEN supplier2 THEN 'supplier2'
              WHEN supplier3 THEN 'supplier3'
              WHEN supplier4 THEN 'supplier4'
              WHEN supplier5 THEN 'supplier5'
         END) as column_name_for_min
FROM priceTable  
WHERE partno = 'OL0003';

This would be much simpler if you structured your data better. 如果您更好地组织数据,这将更加简单。 You should have a table PartSuppliers with one row per part and per supplier. 您应该有一个表PartSuppliers ,每个零件和每个供应商一行。

Then you could get the least value in a variety of ways, such as: 然后,您可以通过多种方式获得最小的价值,例如:

select ps.*
from partsuppliers ps
where ps.cost = (select min(ps2.cost)
                 from partsuppliers ps2
                 where ps2.partno = ps.partno
                );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM