使用一个表中的值作为重新记录结果中的列标题来查询7个表

时间:2018-12-10 09:05:05

标签: mysql

我正在使用MySQL版本5.6.39。

我正在处理的应用程序具有以下ERD。

enter image description here

我正试图编写一些SQL来给我以下内容:

enter image description here

基本上,对于给定的客户参考,在旅程的开始和结束之间,我希望选择AccelerationScore,BreakingScore,CorneringScore,SpeedingScore和DrivingScore。

Here's an MCVE

这是我的代码

SELECT
    v.VehicleReference,
    j.EndDateTime,
    COUNT(sp.SpeedingEventId) AS SpeedingCount
FROM
    AccountAndDevices.Journey j
INNER JOIN
    AccountAndDevices.Device d ON j.DeviceId = d.DeviceId
INNER JOIN
    AccountAndDevices.Vehicle v ON d.VehicleId = v.VehicleId
INNER JOIN
    AccountAndDevices.Account a ON a.AccountId = v.AccountId
LEFT OUTER JOIN
        AccountAndDevices.SpeedingEvent sp On j.DeviceId = sp.DeviceId
    AND
        sp.DateTime BETWEEN j.StartDateTime AND j.EndDateTime
WHERE
        a.AccountReference = 'TestUser03@example.com'
    AND
        JourneyId =
            (SELECT
                JourneyId
            FROM
                AccountAndDevices.Journey j
            INNER JOIN
                AccountAndDevices.Device d ON j.DeviceId = d.DeviceId
            INNER JOIN
                AccountAndDevices.Vehicle v ON d.VehicleId = v.VehicleId
            INNER JOIN
                AccountAndDevices.Account a ON a.AccountId = v.AccountId
            WHERE
                    a.AccountReference = 'TestUser03@example.com'
                AND
                    j.EndDateTime <= NOW()
            ORDER BY
                j.EndDateTime
            DESC
            LIMIT
                1)
GROUP BY
    v.VehicleReference,
    j.EndDateTime;

这让我很接近,但是却错过了所有分数,并且我正努力从JourneyScores表中获取分数,并将其类型(在ScoreType表中)作为列标题。

0 个答案:

没有答案