laravel 求和和交叉表

laravel sum and crosstab

嗨,我正在尝试从 2 天开始解决这个问题,请帮忙。我有一个 table 如下所示。我正在尝试显示交叉表

支出

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 station2 的值将是月费用的总和

这是您要求的 mysql 查询,如果您不知道如何 运行 原始查询,请使用 Laravel 查询生成器 运行 此查询作为原始查询laravel 中的查询让我知道,同时 运行 phpmyadmin/mysql 客户端中的查询,看看它是否为您提供所需的输出。

    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 个站,如果站是未知数那么你可以使用准备好的语句并动态创建它: