T-SQL获得最大值

时间:2012-03-06 18:34:32

标签: sql

我有以下查询

    SELECT  P.ID, MAX(ENTERDATE) as ENTERDATE, MAX(B.CostID) as CostID 
    FROM Protocol P JOIN BANK B ON P.ID= B.ID                                   
    group by P.ID

我需要找出最大的enterdate和相应的CostID,但我不想使用MAX(B.CostID),但我被迫 这样做,因为我有一个P.ID组,所有其他领域需要有某种聚合。我怎么说P.ID分组并告诉我max(enterdate)但是给我相应的那个Enterdate的CostID?

3 个答案:

答案 0 :(得分:3)

 SELECT  P.ID, 
         ENTERDATE  = MAX(p.ENTERDATE), 
         CostID     = (SELECT CostID FROM Bank WHERE ID = p.ID)
  FROM  Protocol P                   
  group by P.ID

或类似

SELECT  t.*,
        CostID
  FROM  Bank b
        JOIN (
                SELECT  P.ID, 
                         ENTERDATE  = MAX(p.ENTERDATE)
                   FROM  Protocol P                   
                   group by P.ID                
             ) t ON t.ID = b.ID

答案 1 :(得分:1)

为什么不查询它:

SELECT MaxTable.*, BANK.CostID AS CostID  
FROM 
(
    SELECT  P.ID, MAX(ENTERDATE) AS ENTERDATE
    FROM Protocol P                                  
    GROUP BY P.ID
) AS MaxTable
JOIN BANK 
    ON MaxTable.ID = BANK.ID

答案 2 :(得分:0)

您可以尝试使用分析函数ROW_NUMBER:

SELECT *
FROM
    (SELECT p.id, p.enterdate, b.costid, 
        ROW_NUMBER() OVER(PARTITION BY p.id ORDER BY p.enterdate DESC) AS rownum
    FROM Protocol P JOIN BANK B ON P.ID= B.ID)
WHERE rownum = 1