如果列名与关键字sql匹配,则为sum列

时间:2015-04-21 09:58:28

标签: php mysql mysqli

我根据系统中每个月的条目,根据费用,收入和交易日期从表中获得记录。

我的查询工作正常,但我有一些方案来扩展此查询。

我有一个名为description的列。我在查询中需要做的是description=='deposit',因此每个月应基于amounts对所有description=='deposit'求和。

示例:

我已经在jan中存了25000,然后在feb中存了3455,然后在每个月再次存入34566,等等。

这是我的查询,但每个月都没有过滤:

SELECT
    MONTH (transaction_date),
    SUM(amount) AS total_amount,
    (SELECT SUM(amount) as deposit FROM tbl_finanace WHERE description = 'Deposit'),
    SUM(IF(amount < 0, amount, 0)) AS expenses,
    SUM(IF(amount > 0, amount, 0)) AS earning,
    transaction_date
FROM
    `tbl_finanace`
WHERE
    transaction_date LIKE '%2015%'
AND user_id = '15'
GROUP BY
    MONTH (transaction_date)
ORDER BY
    MONTH (transaction_date)

1 个答案:

答案 0 :(得分:1)

可以使用条件和

进行如下计算
SUM(case when description = 'Deposit' then amount else 0 end) AS deposit