MySQL内连接与额外的内连接?

时间:2018-11-15 21:10:51

标签: mysql inner-join greatest-n-per-group

我有一个内部联接,有时会为同一Re​​source,Delivery_Datetime,Submit_Time组合返回两行。我只想要基于Other_Time的一行。我认为这是派生的每组最大n上的每组最大n。

SELECT a.Resource, a.Production, a.Submit_Time, a.Delivery_Datetime, a.Other_Time 
FROM foo AS a
INNER JOIN (SELECT Resource, Production, max(Submit_Time) as max_Submit, Delivery_Datetime, Other_Time
            FROM foo 
            WHERE Submit_Time < '2012-01-01 19:00:00' AND Delivery_Date = '2012-01-01 23:00:00'
            GROUP BY Resource, Delivery_Datetime) AS b
ON a.Resource = b.Resource AND a.Delivery_Datetime = b.Delivery_Datetime AND a.Submit_Time = b.max_Submit;

这给我基于Submit_Time的“ 2012-01-01 23:00:00”的Delivery_Datetime的“ 2012-01-01 19:00:00”之前的最新条目,这很好,问题是有时资源的多个条目Delivery_Datetime具有相同的Submit_Time。如果是这种情况,我想选择一个最新的“ Other_Time”

如果我需要另一个内部联接,谁能阐明一些想法?子查询?我尝试了很多东西,包括:

SELECT a.Resource, a.Production, a.Submit_Time, a.Delivery_Datetime, a.Other_Time 
FROM foo AS a
INNER JOIN (SELECT Resource, Production, max(Submit_Time) as max_Submit, Delivery_Datetime, Other_Time
            FROM foo 
            WHERE Submit_Time < '2012-01-01 19:00:00' AND Delivery_Date = '2012-01-01 23:00:00'
            GROUP BY Resource, Delivery_Datetime) AS b
ON a.Resource = b.Resource AND a.Delivery_Datetime = b.Delivery_Datetime AND a.Submit_Time = b.max_Submit
INNER JOIN(SELECT Resource, Production, Submit_Time, Delivery_Datetime, max(Other_Time) as max_Other
           FROM foo 
           WHERE Submit_Time < '2012-01-01 19:00:00' AND Delivery_Datetime = '2012-01-01 23:00:00'
           GROUP BY Resource, Delivery_Datetime, Submit_Time) AS c
ON a.Resource = c.Resource AND a.Delivery_Datetime = c.Delivery_Datetime AND a.Other_Time = c.max_Other

我也尝试过:

SELECT *
FROM  (
    SELECT ns.Resource_Name, ns.Delivery_Datetime, max(ns.submit_time) as max_submit
    FROM (
            SELECT Resource_Name, Delivery_Datetime, submit_time, max(Other_Time) as max_Other
            FROM foo
            WHERE Submit_Time < '2012-01-01 19:00:00'
            GROUP BY Delivery_Datetime, Resource_Name, Submit_Time
    ) as ns
    WHERE ns.Submit_Time < '2012-01-01 19:00:00'
    GROUP BY ns.Delivery_Datetime, ns.Resource_Name
) as sq
JOIN foo as t
ON sq.Resource_Name = t.Resource_Name 
    AND sq.max_submit = t.Submit_Time 
    AND sq.Other_Time = t.Other_Time 
    AND sq.Delivery_Datetime = t.Delivery_Date 
WHERE Submit_Time < '2012-01-01 19:00:00' AND Delivery_Date = '2012-01-01 23:00:00';

谢谢

0 个答案:

没有答案