基于mysql条件的查询

时间:2011-10-20 07:47:34

标签: mysql

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         -

对于每个成员,当tran_points列='+'中的数据时,需要添加plus_minus中的所有值,并且当plus_minus ='中的数据时,需要减去tran_points中的值的总和 - '

我希望得到以下输出:

member_id   points_balance
--------------------------
   2            85
   3            50

5 个答案:

答案 0 :(得分:0)

您可以使用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

希望有所帮助:)

答案 1 :(得分:0)

对于下表:

CREATE TABLE t_test
 (a INTEGER,
  b INTEGER,
  c VARCHAR(1)
 );

以及以下条目:

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,'+');

此查询按预期工作:

SELECT a,SUM((CONCAT(c,b)) +0) as t FROM t_test group by a;

a   t
1   65
2   70

答案 2 :(得分:0)

与答案类似

SELECT member_id,
    SUM(例如,当plus_minus ='+'那么tran_type ELSE(-1)* tran_type)END)AS points_balance FROM tableX GROUP BY member_id



附:在某些DB中,tran_type应该是float或double ..

答案 3 :(得分:0)

你能试试下面提到的sql吗?你不需要使用if条件。 SELECT mem_id AS member_id,     SUM(tran_type)AS points_balance 来自your_table GROUP BY member_id

答案 4 :(得分:0)

您也可以使用

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