I’m using a SQL question were I want to find the lowest value from the field prod_week.
This is the query:
SELECT
MIN(oe.prod_week), oe.prodplan_id
FROM
pd_mounting_details as md
LEFT OUTER JOIN
pd_order_eco AS oe ON md.order_data = oe.id
LEFT OUTER JOIN
pd_article AS a ON md.article = a.id
WHERE
oe.status = 4
AND (md.starttime = '' OR md.starttime IS NULL)
AND (a.production_group = 4)
AND (NOT (oe.amount = 0))
GROUP BY
oe.prodplan_id
The result of this is
prod_week | prodplan_id
1126 | 27
1127 | 28
What I don’t understand is why this result in two rows when I used MIN(prod_week) to get the row with the lowest week number.
If I remove the prodplan_id from the selection it all works and I get one row were prod_week is “1126”. And from that all I want is to get the id prodplan_id to.
I hope this question isn’t to blurry?
When you do
what you’re doing is getting
yand the smallest value ofxfor each distinct value ofy. So, sinceprodplan_idhas values of 27 and 28 in your morass of joins, we have that the smallest value ofprod_weekthat appears whenprodplan_id=27is 1126, and the smallest value ofprod_weekthat appears whenprodplan_id=28is 1127.ETA: If you want one row, you could do an
order by 1 limit 1at the end.ETA^2: You can also wrap things up in a subquery and use a where clause at the end: