3

我只是不能在一个查询中解决这个问题。表TblQcProduction有一个生产订单上每个操作员的记录。

我需要找出根据生产订单报告的最后一个操作员是谁。

SELECT  IDX, ProdOrder, Operator
FROM dbo.TblQCProduction

回报:

IDX     ProdOrder  Operator
8050745 325184     13012
8050746 325184     13035
8050747 325184     13036
8050748 325186     13005
8050749 325186     13038
8050750 325187     13022
8050751 325191     13022
8050752 325191     13035

我需要输出(通过 prodOrder 返回 MAX IDX 的运算符):

IDX     ProdOrder Operator
8050747 325184    13036
8050749 325186    13038
8050750 325187    13022
8050752 325191    13035

我对分组或子查询不满意——我觉得会有一个非常简单的答案。

4

4 回答 4

2

您需要使用ROW_NUMBER() OVER

select IDX,ProdOrder,Operator 

from 
(
select IDX,ProdOrder,Operator,
       ROW_NUMBER() OVER 
         (PARTITION BY ProdOrder ORDER BY IDX DESC) as rn
from TblQCProduction
) as T
WHERE RN=1;

SQLFiddle 演示

于 2013-09-26T11:44:00.990 回答
1

试试这个——

DECLARE @temp TABLE
(
    IDX INT, ProdOrder INT, Operator INT
)

INSERT INTO @temp (IDX, ProdOrder, Operator)
VALUES 
    (8050745, 325184, 13012),
    (8050746, 325184, 13035),
    (8050747, 325184, 13036),
    (8050748, 325186, 13005),
    (8050749, 325186, 13038),
    (8050750, 325187, 13022),
    (8050751, 325191, 13022),
    (8050752, 325191, 13035)

SELECT t.IDX, t.ProdOrder, t.Operator
FROM ( 
    SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY ProdOrder ORDER BY IDX DESC) 
    FROM @temp
) t
WHERE t.rn = 1

输出 -

IDX         ProdOrder   Operator
----------- ----------- -----------
8050747     325184      13036
8050749     325186      13038
8050750     325187      13022
8050752     325191      13035
于 2013-09-26T11:44:53.873 回答
0

我喜欢加入:

SELECT midx, t.prodorder, tt.operator 
FROM  (
  SELECT MAX(idx) AS midx, prodorder
  FROM dbo.TblQCProduction GROUP BY prodorder
) t LEFT JOIN dbo.TblQCProduction tt ON t.midx=tt.idx
于 2013-09-26T11:57:33.070 回答
0
;WITH MyCTE AS
(
    SELECT IDX,
           ProdOrder,
           Operator
           ROW_NUMBER() OVER (PARTITION BY ProdOrder ORDER BY IDX DESC) AS RowNum
    FROM   TblQCProduction
)

SELECT IDX,
       ProdOrder,
       Operator 
FROM MyCTE 
WHERE RowNum = 1
于 2013-09-26T11:45:07.293 回答