我在mysql表中有以下数据名为wallet_txns。
wlt_name wlt_txn_type wlt_txn_amount
A Income 200
A Expense 100
B Income 100
B Income 500
B Expense 200
我试图得到如下数据的输出(单行收入和费用之和)
Wlt_name Expense Income
A 100 200
B 200 600
我使用了以下查询,但我没有按预期得到输出,(获得单独行的收入和费用)请帮助......
select
wlt_name,
if(wlt_txn_type = 'Expense', wlt_txn_amount, 0) as Expense,
if(wlt_txn_type = 'Income', wlt_txn_amount, 0) as Income
from wallet_txns
;
答案 0 :(得分:1)
也许您可以帮助这部分代码:SUM(IF(wlt_txn_type = "Income", wlt_txn_amount, 0)) AS IncomeTotal
。
答案 1 :(得分:0)
您可以使用conditional sum
,然后使用group by
select
wlt_name,
sum(
case when wlt_rxn_type ='Income' then wlt_txn_amount else 0 end
) as `Income`,
sum(
case when wlt_rxn_type ='Expense' then wlt_txn_amount else 0 end
) as `Expense`
from wallet_txns group by wlt_name;
答案 2 :(得分:0)
你可以这样做:
SELECT
Wlt_name,
SUM(CASE WHEN wlt_txn_type='Expense' THEN wlt_txn_amount ELSE 0 END) AS Expense,
SUM(CASE WHEN wlt_txn_type='Income' THEN wlt_txn_amount ELSE 0 END) AS Income
FROM
wallet_txns
GROUP BY
Wlt_name
答案 3 :(得分:0)
您几乎已经编写了正确的查询,但忘了sum
和group
。在这里查询:
select
wlt_name,
sum(if(wlt_txn_type = 'Expense', wlt_txn_amount, 0)) as Expense,
sum(if(wlt_txn_type = 'Income', wlt_txn_amount, 0)) as Income
from wallet_txns
group by wlt_name
;
答案 4 :(得分:0)
我不是mysql用户,但TSQL对我来说没什么秘诀。检查WWW上的PIVOT - UNPIVOT替代品。