我觉得这很容易,但它证明比它应该更难.
目前,我在表格中的每条记录都有几个价格字段(sale_price,retail_price,discounted_price,other_price),但我想只得到最高和最低的非零值.
这适用于最高价值:
SELECT GREATEST(retail_price, sale_price, discounted_price, other_price) AS highest_price FROM TABLE
Run Code Online (Sandbox Code Playgroud)
但是,数据库中没有值的字段存储为零,因此找到非零的最小值证明是具有挑战性的.这不起作用:
SELECT LEAST(retail_price, sale_price, discounted_price, other_price) AS lowest_price FROM TABLE
Run Code Online (Sandbox Code Playgroud)
因为它返回零.
是否有一种简单的方法可以从列表中获取非零最小值,只需对语句进行简单修改即可?
任何帮助/推动正确的方向非常感谢!
示例数据:
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
Run Code Online (Sandbox Code Playgroud)
理想的过滤结果应该是什么:
stock_number highest_price lowest_price
1 999 777
2 55 11
3 0 0
Run Code Online (Sandbox Code Playgroud)
IF如果数字等于零,您可以使用条件返回可能的最大整数。我使用模而不是附加的IFfor 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)
Run Code Online (Sandbox Code Playgroud)