我有一个稍微复杂的SQL语句,但是我不知道在哪里放置WHERE子句

时间:2019-02-06 17:04:05

标签: mysql

我不知道在哪里放置WHERE子句。在driverstops表中,我有一个名为delivdate的字段,表损坏日志中有一个名为dateofdelivery的字段。我想指定特定的日期范围。我在哪里可以放置WHERE子句来限制数据?

SELECT 
    dr.drivername,
    sumStops,
    perfectcnt/sumStops * 100 AS perfpcnt,
    qualcnt/sumStops * 100 AS qualpcnt,
    compcnt/sumStops * 100 As comppcnt,
    damacnt/sumStops * 100 AS damapcnt,
    nofitcnt/sumStops * 100 AS nofitpcnt,
    incocnt/sumStops * 100 AS incopcnt,
    misscnt/sumStops * 100 AS misspcnt,
    notlcnt/sumStops * 100 AS notlpcnt,
    noupcnt/sumStops * 100 AS nouppcnt,
    failccnt/sumStops * 100 AS failcpcnt,
    failscnt/sumStops * 100 AS failspcnt,
    conccnt/sumStops * 100 AS concpcnt,
    nocodcnt/sumStops * 100 AS nocodpcnt,
    failicnt/sumStops * 100 AS failipcnt
FROM drivers dr
LEFT JOIN (
    SELECT
        driverid,
        SUM(numberofstops) sumStops
    FROM driverstops
    GROUP BY driverid
) stops ON dr.id = stops.driverid
LEFT JOIN (
    SELECT
        driverid,
        damagelog.dateofdelivery date,
        SUM(perfect) perfectcnt,
        SUM(quality) qualcnt,
        SUM(compliment) compcnt,
        SUM(damage) damacnt,
        SUM(nofit) nofitcnt,
        SUM(incomplete) incocnt,
        SUM(misseddeliv) misscnt,
        SUM(notloaded) notlcnt,
        SUM(noupdate) noupcnt,
        SUM(failcall) failccnt,
        SUM(failsendemail) failscnt,
        SUM(concerns) conccnt,
        SUM(nocod) nocodcnt,
        SUM(failinst) failicnt
    FROM damagelog
    GROUP BY driverid
) dam ON dr.id = dam.driverid

1 个答案:

答案 0 :(得分:0)

就您所关注的而言,您要过滤的列来自聚合子查询,然后对这些子查询进行JOIN处理。在一个联接(driverstops)中,子查询没有返回您要过滤的字段。

似乎最简单的解决方案是在每个子查询中放置一个WHERE子句,例如:

LEFT JOIN (
    SELECT driverid,SUM(numberofstops) sumStops
    FROM driverstops
    WHERE delivdate BETWEEN @stat_date AND @end_date
    GROUP BY driverid
) stops ON dr.id = stops.driverid

然后:

LEFT JOIN (
    SELECT
        driverid,
        damagelog.dateofdelivery date,
        SUM(perfect) perfectcnt,
        ...
    FROM damagelog
    WHERE dateofdelivery BETWEEN @stat_date AND @end_date
    GROUP BY driverid
) dam ON dr.id = dam.driverid