使用MIN()获得最低值,但我有两行?

时间:2011-08-10 17:50:27

标签: sql-server

我想使用SQL问题,我想找到字段prod_week中的最低值。

这是查询:

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

结果是

prod_week      |  prodplan_id
  1126         |     27
  1127         |     28

我不明白为什么当我使用MIN(prod_week)获取具有最低周数的行时,这会产生两行。

如果我从选择中移除prodplan_id,则一切正常,我得到一行,prod_week是" 1126"。从中我想要的就是获得id prodplan_id

我希望这个问题不会模糊吗?

3 个答案:

答案 0 :(得分:4)

您正在使用GROUP BY,这意味着每GROUP行将获得一行。

在这种情况下,您的GROUPprodplan_id,并且有两个匹配值。

要获得这两个值,您可以尝试:

SELECT 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 

WHERE oe.prod_week = (SELECT MIN(oe.prod_week)
                      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))) 

答案 1 :(得分:2)

当你这样做时

select min(x),y
from table
group by y;

您正在做的是为y的每个不同值获取xy的最小值。因此,由于prodplan_id在您的连接泥潭中的值为27和28,因此prod_week为{11}时出现prodplan_id=27的最小值,prod_week的最小值为prodplan_id=28order by 1 limit 1为1127时出现的那个。

ETA:如果你想要一行,你最后可以做select min_prod_week,prodplan_id from( select min(oe.prod_week) as min_prod_week,oe.prodplan_id from.... group by oe.prodplan_id )min where min_prod_week=(select min(prod_week) from pd_order_eco)

ETA ^ 2:你也可以在子查询中包装并在最后使用where子句:

{{1}}

答案 2 :(得分:1)

由于您的select语句以group by子句结尾,因此您为每个prodplan_id选择最小prod_week而不是总体最小值。删除group by子句,它应该按预期工作。