每组选择一列中的最小值

时间:2019-01-22 14:48:00

标签: sql-server ms-access-2010

我有一个看起来像下面的表,它是使用以下代码创建的...

SELECT Orders.ID, Orders.CHECKIN_DT_TM, Orders.CATALOG_TYPE, 
Orders.ORDER_STATUS, Orders.ORDERED_DT_TM, Orders.COMPLETED_DT_TM, 
Min(DateDiff("n",Orders.ORDERED_DT_TM,Orders.COMPLETED_DT_TM)) AS 
Time_to_complete

FROM Orders

GROUP BY Orders.ORDER_ID, Orders.ID,
Orders.CHECKIN_DT_TM, Orders.CATALOG_TYPE, Orders.ORDERED_DT_TM, 
Orders.COMPLETED_DT_TM, HAVING (((Orders.CATALOG_TYPE)="radiology");

ID  Time_to_complete ... .....
1        5
1        7
1        8
2        23
2        6
3        7
4        16
4        14

我想添加到此代码中,该代码将为每个主题ID选择最小的Time_to_complete值。离开所需的表:

ID  Time_to_complete ... .....
1        5
2        6
3        7
4        14

我正在使用Access,并且希望继续使用Access来完成此代码,但是如果在Access中无法使用SQL Server,则可以选择使用SQL Server。谢谢!

3 个答案:

答案 0 :(得分:1)

我怀疑您需要相关子查询:

SELECT O.*, DateDiff("n", O.ORDERED_DT_TM, O.COMPLETED_DT_TM) AS Time_to_complete
FROM Orders O
WHERE DateDiff("n", O.ORDERED_DT_TM, O.COMPLETED_DT_TM) = (SELECT Min(DateDiff("n", O1.ORDERED_DT_TM, O1.COMPLETED_DT_TM))     
                                                           FROM Orders O1
                                                           WHERE O1.ORDER_ID = O.ORDER_ID AND . . . 
                                                          );

编辑::如果您想要唯一的记录,则可以这样做:

SELECT O.*, DateDiff("n", O.ORDERED_DT_TM, O.COMPLETED_DT_TM) AS Time_to_complete
FROM Orders O
WHERE o.pk = (SELECT TOP (1) o1.pk  
              FROM Orders O1
              WHERE O1.ORDER_ID = O.ORDER_ID AND . . . 
              ORDER BY DateDiff("n", O.ORDERED_DT_TM, O.COMPLETED_DT_TM) ASC
             );

pk是您的标识列,它在Orders表中指定唯一条目,因此您可以相应地对其进行更改。

答案 1 :(得分:1)

看看这个:

DECLARE @myTable AS TABLE (ID INT, Time_to_complete INT);

INSERT INTO @myTable
VALUES (1, 5)
,      (1, 7)
,      (1, 8)
,      (2, 23)
,      (2, 6)
,      (3, 7)
,      (4, 16)
,      (4, 14);

WITH cte AS
    (SELECT *
     ,      ROW_NUMBER() OVER (PARTITION BY ID  ORDER BY Time_to_complete) AS RN
       FROM @myTable)
SELECT  cte.ID
,       cte.Time_to_complete
  FROM  cte
 WHERE  RN = 1;

结果:

ID          Time_to_complete
----------- ----------------
1           5
2           6
3           7
4           14

它在组上使用行号,然后为每个组选择第一行。您应该能够调整代码以使用此技术。如果有疑问,请先将整个查询包装在cte中,然后在此处应用该技术。

值得在很多地方使用此过程,尤其是在重复数据删除方面。

答案 2 :(得分:0)

Try This 

    DECLARE @myTable AS TABLE (ID INT, Time_to_complete INT);

    INSERT INTO @myTable
    VALUES (1, 5)
    ,      (1, 7)
    ,      (1, 8)
    ,      (2, 23)
    ,      (2, 6)
    ,      (3, 7)
    ,      (4, 16)
    ,      (4, 14);


    SELECT  O.ID, O.Time_to_complete 
    FROM @myTable O
    WHERE o.Time_to_complete  = (Select min(m.Time_to_complete) FROM @myTable m
                                                        Where o.id=m.ID
                                                              );


Result :

ID  Time_to_complete
1   5
2   6
3   7
4   14