SQL Server子查询的新手 - 希望是一个简单的查询

时间:2013-09-26 11:39:39

标签: sql sql-server in-subquery

我不能在一个查询中解决这个问题。 表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 个答案:

答案 0 :(得分: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 demo

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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