您好我正在努力创造一些东西,但我的总数不是负数。所以基本上我得到的是负值,可以乘以一个有点复杂的数学方程。
所以......用户输入的数据从-1到1.(-1,0,1) 它会在我的公式中成倍增加。所以我的SQL查询看起来像这样......(这部分有效!)
SELECT *, a, b, c AS TOTALNUMBER FROM MATH
ORDER BY TOTALNUMBER DESC
但是,我需要总数为正数。所以我在过去的几个小时里一直试图解决这个问题。我是php / sql的新手。
我想尝试包括......
if (TOTALNUMBER < 0 ) {
TOTALNUMBER * -1.0
}
但是我不知道在查询中包含这个内容或者如何正确编写它。
澄清和更新我要找的东西...... 用户可以输入-1,0,1
例如,A,B,C的数据。 10,15,20 用户输入:1,-1,0
A total = 10
B total = -15
C total = 0
Total ABC = -5
但是,我需要总数为5而不是-5而不更改任何A,B,C值。
答案 0 :(得分:4)
use like this
SELECT *, a, b, ABS(c) AS TOTALNUMBER FROM MATH
ORDER BY TOTALNUMBER DESC
答案 1 :(得分:1)
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used.
SELECT a, b, c, If (c <0 , c * -1, c) AS TOTALNUMBER FROM MATH
ORDER BY TOTALNUMBER DESC;
If you want the sum of all the fields to be your total number, assuming you have an id field:
SELECT a,b,c,ABS((sum(a)+(b)+(c))) AS TOTALNUMBER FROM MATH
group by mathid ORDER BY TOTALNUMBER DESC;
Here is an example:
mysql> select * from math;
+--------+----------+
| idmath | mathcol1 |
+--------+----------+
| 1 | 1 |
| 2 | 3 |
| 3 | -1 |
| 4 | -3 |
+--------+----------+
4 rows in set (0.00 sec)
mysql> SELECT idmath, If (mathcol1 <0 , mathcol1 * -1, mathcol1) AS TOTALNUMBER
FROM MATH ORDER BY TOTALNUMBER DESC;
+--------+-------------+
| idmath | TOTALNUMBER |
+--------+-------------+
| 2 | 3 |
| 4 | 3 |
| 1 | 1 |
| 3 | 1 |
+--------+-------------+
4 rows in set (0.00 sec)
mysql> SELECT idmath, mathcol1, If (mathcol1 <0 , mathcol1 * -1, mathcol1) AS TO
TALNUMBER FROM MATH ORDER BY TOTALNUMBER DESC;
+--------+----------+-------------+
| idmath | mathcol1 | TOTALNUMBER |
+--------+----------+-------------+
| 2 | 3 | 3 |
| 4 | -3 | 3 |
| 1 | 1 | 1 |
| 3 | -1 | 1 |
+--------+----------+-------------+
4 rows in set (0.00 sec)
mysql> SELECT mathcol1,mathcol2,mathcol3, (sum(ABS(mathcol1))+(mathcol2)+(mathco
l3)) AS TOTALNUMBER FROM MATH group by idmath ORDER BY TOTALNUMBER DESC;
+----------+----------+----------+-------------+
| mathcol1 | mathcol2 | mathcol3 | TOTALNUMBER |
+----------+----------+----------+-------------+
| 3 | 2 | 3 | 8 |
| -3 | 2 | 3 | 8 |
| -1 | 2 | 3 | 6 |
| 1 | 2 | 3 | 6 |
+----------+----------+----------+-------------+
4 rows in set (0.00 sec)
You can read more here at dev.mysql.