MySQL选择根据其他字段计算2个字段

时间:2016-08-18 04:55:33

标签: mysql sum

我们说我有一张这样的表

| user | symbol | status | value |
----------------------------------
| 101  | A      | 1      | 20    |
| 102  | A      | 1      | 20    |
| 103  | A      | 1      | 20    |
| 101  | A      | 0      | 20    |
| 102  | B      | 1      | 20    |
| 103  | A      | 1      | 20    |
| 101  | A      | 0      | 20    |
| 102  | A      | 1      | 20    |
| 103  | A      | 0      | 20    |
| 101  | B      | 1      | 20    |
| 102  | A      | 0      | 20    |

我希望得到这样的结果(所有值都改为负值,状态= 0)

| user | symbol | differences |
----------------------------------
| 101  | A      | -20         |
| 101  | B      | 20          |
| 102  | A      | 20          |
| 102  | B      | 20          |
| 103  | A      | 20          |

请帮助,任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

使用以下CASE..WHEN的通用解决方案:

SELECT user,
       symbol,
   CASE WHEN status > 0 THEN value
        ELSE -value END as differences
 FROM yourTable;

虽然在这种特殊情况下,您也可以使用数学:

SELECT user, 
       symbol,
       (value * (2*status-1)) as differences
  FROM yourTable;

如果您还想汇总结果,则可以更改上面的查询,以使用GROUP BY SUM作为聚合:

SELECT  user,
       symbol,
   SUM(CASE WHEN status > 0 THEN value
        ELSE -value END) as differences
 FROM yourTable
GROUP BY user, symbol;

等效的聚合查询,使用算术:

SELECT user, 
       symbol,
       SUM(value * (2*status-1)) as differences
  FROM yourTable
 GROUP BY user, symbol;

答案 1 :(得分:1)

如果CASE = 0,请使用status表达式将值更改为减号。

<强>查询

 select `user`, `symbol`, 
 sum(case when `status` = 0 then `value` * -1 else `value` end) as differences
 from `your_table_name`
 group by `user`, `symbol`
 order by `user`, `symbol`;

SQL Fiddle demo