I have seen many "N values in GROUP BY," but I need it twice. I have:
CREATE TABLE foo(PK INT(11) NOT NULL, Delivery_Date DATE, Hour_Ending TIME(0),
Resource VARCHAR(26), Rate FLOAT, Submit_Time DATETIME(0), Eff_stop DATETIME(0), PRIMARY KEY (PK));
insert into foo values(1,'2017-01-04','07:00:00','Plant_BAR','10','2017-01-03 05:00:00','2017-01-03 06:22:00'),
(2,'2017-01-04','07:00:00','Plant_BAR','9','2017-01-03 06:00:00','2017-01-03 06:55:00'),
(3,'2017-01-04','07:00:00','Plant_BAR','10','2017-01-03 06:00:00','2017-01-03 08:22:00'),
(4,'2017-01-04','07:00:00','Plant_BAR','10','2017-01-03 07:55:00','2017-01-03 08:53:00'),
(5,'2017-01-04','07:00:00','Plant_BAzz','50','2017-01-03 13:04:00','2017-01-07 06:22:00'),
(6,'2017-01-04','08:00:00','Plant_BAR','10','2017-01-03 05:00:00','2017-01-03 06:22:00'),
(7,'2017-01-04','07:00:00','Plant_BAzz','55','2017-01-03 05:00:00','2017-01-03 06:22:00'),
(8,'2017-01-04','07:00:00','Plant_BAR','0','2017-01-03 10:00:00','2017-01-03 06:22:00');
I need a point in time effective Rate by Resource, Delivery_Date, Hour_Ending which depends on Submit_Time and Eff_Stop. I am running into issues when the Subimit_Time is identical for the same Resource, Hour_Ending, and Delivery_Date.
I want the max(Submit_Time) row returned, and if there is two identical submit times, I want the row with the max(Eff_Stop)
I have:
SELECT a.PK, a.Delivery_Date, a.Hour_Ending, a.Resource, a.Rate, a.Submit_Time, a.Eff_Stop
FROM foo as a
INNER JOIN (SELECT Resource, Delivery_Date, Hour_Ending, max(Submit_Time) as max_submit
FROM foo
WHERE (Submit_Time < cast(Delivery_Date as datetime)-interval 1 day + interval 7 hour)
AND (Delivery_Date ='2017-01-04') and (Hour_Ending ='07:00:00')
GROUP BY Resource, Delivery_Date, Hour_Ending
) as b
ON a.Resource = b.Resource and a.Delivery_Date = b.Delivery_Date and a.Hour_Ending = b.Hour_Ending and a.Submit_Time = b.max_submit
WHERE (a.Delivery_Date ='2017-01-04') and (a.Hour_Ending ='07:00:00')
GROUP BY a.Hour_Ending, a.Delivery_Date, a.Resource;
This lets me return 1 row per Resource which is the most current Submit_Time, but when a Resource has and identical Submit_Time (in this case '2017-01-03 06:00:00') I want to then pick the one with the max(Eff_Stop).
The result is:
PK Delivery_Date Hour_Ending Resource Rate Submit_Time Eff_stop
2 2017-01-04 07:00:00 Plant_BAR 9 2017-01-03T06:00:00Z 2017-01-03T06:55:00Z
7 2017-01-04 07:00:00 Plant_BAzz 55 2017-01-03T05:00:00Z 2017-01-03T06:22:00Z
I want:
PK Delivery_Date Hour_Ending Resource Rate Submit_Time Eff_stop
3 2017-01-04 07:00:00 Plant_BAR 10 2017-01-03T06:00:00Z 2017-01-03T08:22:00Z
7 2017-01-04 07:00:00 Plant_BAzz 55 2017-01-03T05:00:00Z 2017-01-03T06:22:00Z
http://sqlfiddle.com/#!9/5cb999/1/0
I have tried a left and right join, two inner joins, and a bunch of other garbage that doesn't work.
Any help would be greatly appreciated!