2015-05-29 65 views
0

我在mysql表中有以下數據稱爲wallet_txns。根據數據類型在單行中輸出mysql表數據

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

您是否聽說過聚合函數? – agad

+0

你想總結的價值,但不使用'總和'功能?怎麼樣?爲什麼? – Strawberry

回答

0

您已經差不多寫了正確的查詢,但忘記了sumgroup。這裏查詢:

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 
; 
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; 
+0

對不起,我忘了把'總和'。感謝所有提醒和支持。 –

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 
1

也許你可以幫助這部分代碼:SUM(IF(wlt_txn_type = "Income", wlt_txn_amount, 0)) AS IncomeTotal

0

我不是mysql用戶,但TSQL對我來說沒什麼祕密。檢查WWW上的PIVOT - UNPIVOT備選方案。