[英]mysql condition based query
id mem_id tran_date tran_type tran_points plus_minus
-----------------------------------------------------------
1 2 2011-10-19 test 50 +
2 2 2011-10-19 test 50 +
3 3 2011-10-19 test 50 +
4 2 2011-10-19 test 15 -
For every individual member all the values in tran_points
needs to be added when data in plus_minus
column = '+' and the sum of value in tran_points needs to be substracted when data in plus_minus = '-' 对于每个单独的成员,当
plus_minus
列='+'中的数据时,必须添加tran_points
所有值;而当plus_minus ='-'中的数据时,需要减去tran_points中的值总和。
I want to have the following output : 我想要以下输出:
member_id points_balance
--------------------------
2 85
3 50
You can do this with a SUM(IF()) type of clause as follows; 您可以使用SUM(IF())类型的子句来执行此操作,如下所示;
SELECT mem_id AS member_id,
SUM( IF(plus_minus="+", tran_type, (0 - tran_type) ) ) AS points_balance
FROM your_table
GROUP BY member_id
Hope that helps :) 希望有帮助:)
For the table below: 对于下表:
CREATE TABLE t_test
(a INTEGER,
b INTEGER,
c VARCHAR(1)
);
and for the entries below: 以及以下条目:
INSERT INTO t_test values(1,50,'+');
INSERT INTO t_test values(1,30,'+');
INSERT INTO t_test values(1,15,'-');
INSERT INTO t_test values(2,30,'+');
INSERT INTO t_test values(2,40,'+');
This query works as you expected: 此查询按预期工作:
SELECT a,SUM((CONCAT(c,b)) +0) as t FROM t_test group by a;
a t
1 65
2 70
Similar to the answer 类似于答案
SELECT member_id, SELECT member_id,
SUM( CASE WHEN plus_minus='+' THEN tran_type ELSE (-1) * tran_type) END) AS points_balance FROM tableX GROUP BY member_id SUM(CASE WHEN plus_minus ='+'THEN tran_type ELSE(-1)* tran_type)END)AS points_balance from tableX GROUP BY member_id
PS In some DB's tran_type should be float or double.. PS在某些数据库中,tran_type应该为float或double。
Can you try the below mentioned sql. 您可以尝试以下提到的sql吗? You dnt need to use the if condition.
您不需要使用if条件。 SELECT mem_id AS member_id, SUM( tran_type) AS points_balance FROM your_table GROUP BY member_id
SELECT mem_id AS member_id,SUM(tran_type)AS points_balance FROM your_table GROUP BY member_id
您也可以使用
SELECT b.mem_id,SUM(b.tran_points)-(SELECT COALESCE(SUM(a.tran_points),0) FROM tableX AS a WHERE a.plus_minus='-' AND a.mem_id=b.mem_id) AS tran_points FROM tableX AS b WHERE b.plus_minus='+' GROUP BY b.mem_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.