0

我有两个由一个AUTO_KEY字段链接的表,我从一个表中检索数字(id),从另一个表中我通过数字(id)获得几个状态,每个状态都有一个与之关联的日期。我需要将结果限制为所有数字(ID)和相应状态的最大/最新日期

SELECT
    OPERATION.NUMBER, 
    STATUS.STATUS, 
    Max(STATUS.DATE)

FROM 
   STATUS, 
   OPERATION

WHERE 
OPERATION.AUTO_KEY = STATUS.AUTO_KEY 

从这里

Number  Status    Date
-----------------------------
1       A       10/20/13
1       B       10/15/13
2       A       10/10/13
2       AX      10/05/13
2       AD      10/03/13
3       DD      10/03/13

结果应该是

Number  Status    Date
-----------------------------
1       A       10/20/13
2       A       10/10/13
3       DD      10/03/13

提前致谢

4

2 回答 2

1

您可以将CTEROW_NUMBER()函数一起使用。也请使用 aTable JOIN 代替 FROM STATUS, OPERATION

;With CTE AS (
   SELECT O.NUMBER, S.STATUS, S.DATE, 
          ROW_NUMBER() OVER (ORDER BY S.DATE DESC) RN
   FROM  STATUS S JOIN OPERATION O
           ON O.AUTO_KEY = S.AUTO_KEY 
)
SELECT NUMBER, STATUS, DATE
FROM CTE
WHERE RN = 1
ORDER BY NUMBER
于 2013-10-25T20:50:41.977 回答
0
SELECT OPERATION.CNUMBER, 
       STATUS.STATUS, 
       STATUS.CDATE
FROM STATUS, 
     OPERATION
WHERE OPERATION.AUTO_KEY = STATUS.AUTO_KEY 
AND STATUS.CDATE = (
SELECT MAX(STATUS.CDATE) MAX_DATE
FROM STATUS, 
      OPERATION
WHERE OPERATION.AUTO_KEY = STATUS.AUTO_KEY 
GROUP BY OPERATION.CNUMBER )
于 2013-10-26T10:34:46.700 回答