【问题标题】:laravel sum and crosstablaravel 总和和交叉表
【发布时间】:2016-12-03 05:14:31
【问题描述】:

您好,我正在尝试从 2 天内解决此问题,请帮助。我有一张如下表。我正在尝试显示交叉表

支出

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 crosstab


    【解决方案1】:

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

    【讨论】:

    • 谢谢,是的,电台是未知号码,你能告诉我如何使用准备好的声明
    • 是的,但不会显示id不在费用表中的站的结果
    • 我更新了上面的代码,我把内连接换成了左连接,现在试试看
    • 不,它仍然没有显示不在费用表中的电台
    • 我使用了 SELECT exp.name AS 支出,st.name AS 站,x.totalexpense FROM 支出作为 exp LEFT JOIN (SELECT 支出_id,station_id,SUM(expense) 作为总支出从费用 WHERE year = ' 2015' GROUP by demand_id,station_id ) AS x ON exp.id = x.expenditure_id LEFT JOIN station AS st ON x.station_id = st.id 但它只给出费用表中的站的结果任何想法
    猜你喜欢
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多