SQL从聚合函数中获取最小值

时间:2014-12-23 16:54:13

标签: sql sql-server

我正在尝试从agregate函数返回最小值。我创建了一个执行的查询,但无法仅为每个组返回一个最小行。在此示例中,每个prod_num都有多行,每行都有唯一的序列号。这适用于SQL Server。

我的代码:

SELECT 
    x.prod_num, Min(x.sn) sn, y.qty, x.date_tested,x.scrap
FROM 
    serial_numbers x
JOIN 
    prod_ord y on y.prod_num = x.prod_num
WHERE
    x.date_tested IS NOT NULL 
    AND x.scrap = 1
GROUP BY 
    x.prod_num, x.sn, y.qty, x.date_tested, x.scrap
ORDER BY 
    x.date_tested desc, x.prod_num

我的结果:

prod_num    sn            qty   date_tested           scrap
------------------------------------------------------------
301336662   120214A10338    7   2014-12-09 19:26:41.650 1
301336662   120214A10339    7   2014-12-09 19:26:41.650 1
301336662   120214A10340    7   2014-12-09 19:26:41.650 1
301336662   120214A10341    7   2014-12-09 19:26:41.650 1
301336662   120214A10342    7   2014-12-09 19:26:41.650 1
301336662   120214A10343    7   2014-12-09 19:26:41.650 1
301336662   120214A10344    7   2014-12-09 19:26:41.650 1
301303464   101014A11003    4   2014-10-16 15:18:06.817 1
301303464   101014A11004    4   2014-10-16 15:18:06.817 1
301303464   101014A11005    4   2014-10-16 15:18:06.817 1
301303464   101014A11006    4   2014-10-16 15:18:06.817 1
301293879   100714A10258    15  2014-10-13 13:23:58.923 1
301293879   100714A10259    15  2014-10-13 13:23:58.923 1
301293879   100714A10260    15  2014-10-13 13:23:58.923 1
301293879   100714A10261    15  2014-10-13 13:23:58.923 1
301293879   100714A10262    15  2014-10-13 13:23:58.923 1
301293879   100714A10263    15  2014-10-13 13:23:58.923 1
301293879   100714A10264    15  2014-10-13 13:23:58.923 1
301293879   100714A10265    15  2014-10-13 13:23:58.923 1
301293879   100714A10266    15  2014-10-13 13:23:58.923 1

我真正想要获得的是每个prod_num只有一行,sn最小的行。

喜欢这个。

prod_num    sn            qty   date_tested           scrap
------------------------------------------------------------
301336662   120214A10338    7   2014-12-09 19:26:41.650 1
301303464   101014A11003    4   2014-10-16 15:18:06.817 1
301293879   100714A10258    15  2014-10-13 13:23:58.923 1

有人可以指出我出错的地方吗?

谢谢, 比尔

1 个答案:

答案 0 :(得分:3)

从...中删除x.sn ...

您的声明:

SELECT x.prod_num, Min(x.sn) sn, y.qty, x.date_tested,x.scrap
FROM serial_numbers x
JOIN prod_ord y on y.prod_num = x.prod_num
where x.date_tested is not NULL and x.scrap = 1
group by x.prod_num, x.sn, y.qty, x.date_tested,x.scrap
order by x.date_tested desc, x.prod_num

应该是:

SELECT x.prod_num, Min(x.sn) sn, y.qty, x.date_tested,x.scrap
FROM serial_numbers x
JOIN prod_ord y on y.prod_num = x.prod_num
where x.date_tested is not NULL and x.scrap = 1
group by x.prod_num, y.qty, x.date_tested,x.scrap
order by x.date_tested desc, x.prod_num

你告诉引擎按x.sn分组它正在做什么,但你只想要最小的一个。通过从组中删除x.sn,您应该得到所需的结果。