2016-07-28 45 views
-1

嗨,我想從2天解決這個問題,請幫助。我有一張如下表格。我想獲得交叉表顯示laravel sum和crosstab

支出

id name 
1 exp1 
2 exp2 
3 exp3 
4 exp4 
5 exp5 

id name 
1 station1 
2 station2 
3 station3 
4 station4 

費用

expenditure_id station_id year month expense 
1    1   2015 1 10 
1    2   2015 1 20 
1    3   2015 1 15 
1    4   2015 1 10 
1    1   2015 2 20 
1    1   2015 3 30 
1    1   2015 4 40  
2    1   2015 1 20  
2    1   2015 2 10 
2    1   2015 3 20  

我想要獲取的結果是這樣

2015年

expenditure station1 station2 station3 station4 
exp1  100  20  15  0 
exp2  50   0  0   0 

其中STATION1站2的值將月開支的總和

回答

1

這是MySQL查詢作爲您的要求,使用Laravel查詢生成器來運行此查詢作爲原始查詢,如果您不知道如何在laravel中運行原始查詢,請讓我知道,同時在phpmyadmin/mysql客戶端中運行查詢,並查看它是否爲您提供所需的outp ut。

SELECT y.expenditure, 
     MAX(CASE y.station WHEN 'station1' THEN y.totalexpense END) 'station1', 
     MAX(CASE y.station WHEN 'station2' THEN y.totalexpense END) 'station2', 
     MAX(CASE y.station WHEN 'station3' THEN y.totalexpense END) 'station3', 
     MAX(CASE y.station WHEN 'station4' THEN y.totalexpense END) 'station4' 
    FROM (
     SELECT exp.name AS expenditure,st.name AS station,x.totalexpense 
     FROM expenditures AS exp 
     LEFT JOIN 
     (SELECT expenditure_id,station_id,SUM(expense) as totalexpense 
     FROM expenses 
     WHERE year = '2015' 
     GROUP by expenditure_id,station_id 
     ) 
     AS x ON exp.id = x.expenditure_id 
     LEFT JOIN stations AS st ON x.station_id = st.id 
    ) AS y 
    GROUP BY y.expenditure 

我假設你只有4個站,如果站未知號碼,那麼你可以使用一個事先準備好的聲明,並動態地創建此:

+0

謝謝,是站是未知號碼,你可以請出示準備如何使用聲明 – sanu

+0

OK,它給你想要的結果在phpMyAdmin –

+0

是的,但它不會顯示站的ID是不是在費用表 – sanu