您好,我试图从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的值将是月费用的总和
答案 0 :(得分: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个电台,如果电台是未知号码,那么您可以使用预备语句并动态创建: