MySQL查询将列视为正或负,具体取决于另一个值

时间:2013-09-08 03:13:38

标签: mysql

我在MySQL中有一个表格,结构如下:

table1
------
userid  varchar(20)
type    varchar(20)
amount  integer

类型可以是depositwithdrawal

我想在这张桌子上执行查询,在那里我可以获得提款总额的净余额 - 给定用户的存款。

这是可能的MySQL还是我需要运行两个单独的查询并在代码中进行减法?

3 个答案:

答案 0 :(得分:3)

怎么样:

select sum(
          case type
          when 'deposit' then amount
          when 'withdrawal' then -amount
          end 
          ) as balance
from $table where userid = $id

答案 1 :(得分:1)

你可以执行这样的事情。调整表名称和类型值。它将按用户总金额和借方分组,并为您提供余额列。

SELECT userid, 
   Sum(CASE 
         WHEN [type] = 'Deposit' THEN amount 
         ELSE 0 
       END) AS deposit, 
   Sum(CASE 
         WHEN [type] = 'Debit' THEN amount 
         ELSE 0 
       END) AS debit, 
   Sum(CASE 
         WHEN [type] = 'Deposit' THEN amount 
         ELSE amount * -1 
       END) AS Balance 
   FROM   tblaccount 
GROUP  BY userid 

答案 2 :(得分:0)

子查询应该能够这样做:

select 
   (select sum(amount) 
    from table1 
    where type='deposit' 
    and userid = 'user1'
   ) - 
   (select sum(amount) 
    from table1 
    where type='withdrawal' 
    and userid = 'user1') 
 as deposit_minus_withdrawls

或案例陈述。

SELECT userid, SUM( 
  CASE TYPE WHEN  'withdrawal'
  THEN amount
  ELSE 0 
  END ) - 
  SUM( 
  CASE TYPE WHEN  'deposit'
  THEN amount
  ELSE 0 
  END ) AS balance
FROM table1
GROUP BY userid
LIMIT 0 , 30