0

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

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

类型可以是depositwithdrawal

我想在这个表上执行一个查询,在这里我可以获得取款总和的净余额 - 给定用户的存款。

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

4

3 回答 3

3

这个怎么样:

select sum(
          case type
          when 'deposit' then amount
          when 'withdrawal' then -amount
          end 
          ) as balance
from $table where userid = $id
于 2013-09-08T03:22:35.817 回答
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 
于 2013-09-08T04:10:28.783 回答
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
于 2013-09-08T03:28:11.980 回答