我觉得这很容易,但事实证明它比它应该的要难。
目前,我有几个价格字段用于表中的每个记录(sale_price、retail_price、discounted_price、other_price),但我只想获得最高和最低的非零值。
这适用于最高值(value):
SELECT GREATEST(retail_price, sale_price, discounted_price, other_price) AS highest_price FROM TABLE
但是,数据库中没有值的字段存储为零,因此找到非零的最小值被证明具有挑战性。这不起作用:
SELECT LEAST(retail_price, sale_price, discounted_price, other_price) AS lowest_price FROM TABLE
因为它返回零。
是否有一种简单的方法可以通过对语句进行简单修改来从列表中获取非零最小值?
非常感谢任何朝着正确方向的帮助/插入!
示例数据:
stock_number discounted_price sale_price retail_price other_price
1 999 888 0 777
2 55 22 33 11
3 0 0 0 0
理想的过滤结果应该是什么:
stock_number highest_price lowest_price
1 999 777
2 55 11
3 0 0
最佳答案
如果数字等于零,您可以使用 IF
条件返回可能的最大整数。我使用模而不是额外的 IF
用于 IF output is ~0>>32 return 0
。
SELECT *, LEAST(IF(retail_price>0,retail_price,~0>>32),
IF(sale_price>0,sale_price,~0>>32),
IF(discounted_price>0,discounted_price,~0>>32),
IF(other_price>0,other_price,~0>>32))%(~0>>32)
AS lowest_price FROM table_name;
+--------------+------------+------------------+-------------+--------------+
| retail_price | sale_price | discounted_price | other_price | lowest_price |
+--------------+------------+------------------+-------------+--------------+
| 434.28 | 6992.52 | 8969.79 | 11526.37 | 434.28 |
| 6032.47 | 7928.27 | 9198.91 | 9864.75 | 6032.47 |
| 9382.03 | 4970.88 | 9053.33 | 5664.02 | 4970.88 |
| 1160.12 | 1153.51 | 2287.21 | 7975.51 | 1153.51 |
| 8325.92 | 5358.05 | 1812.52 | 5333.46 | 1812.52 |
| 8884.71 | 3733.20 | 4356.84 | 10584.62 | 3733.20 |
| 2817.57 | 7023.99 | 1977.24 | 1159.22 | 1159.22 |
| 12209.40 | 8189.34 | 4318.52 | 9369.54 | 4318.52 |
| 9202.18 | 5557.26 | 179.77 | 8917.08 | 179.77 |
| 0.00 | 1.00 | 2.00 | 3.00 | 1.00 |
| 100.00 | 201.00 | 302.00 | 0.00 | 100.00 |
| 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
+--------------+------------+------------------+-------------+--------------+
12 rows in set (0.00 sec)
关于MySQL:如何选择非零的最小整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38964436/