2011-05-13 74 views
4

我有以下查詢:SQL MAX(DATE)訂單號

SELECT o.ClientId, o.MAX(Date), o.OrderNumber 
FROM dbo.tblOrders 
GROUP BY o.ClientId, o.OrderNumber 

這仍然給了我所有的訂單號碼,我將如何只能得到與MAX日期那張訂單號。

我試圖完成的是獲取每個客戶端的MAX訂單日期並顯示是哪個訂單號。

感謝

回答

7
SELECT t.ClientId, t.MaxDate, o.OrderNumber 
    FROM (SELECT ClientId, MAX(Date) as MaxDate 
       FROM dbo.tblOrders 
       GROUP BY ClientId) t 
     INNER JOIN dbo.tblOrders o 
      ON t.ClientId = o.ClientId 
       AND t.MaxDate = o.Date 

如果你使用的是支持窗口的功能,如SQL Server 2005+的RDBMS,這也可以做到這樣,而不是:

SELECT t.ClientId, t.OrderNumber, t.Date 
    FROM (SELECT ClientId, OrderNumber, Date, 
       ROW_NUMBER() OVER(PARTITION BY ClientId ORDER BY Date DESC) as RowNum 
       FROM dbo.tblOrders 
     ) t 
    WHERE t.RowNum = 1 
0

看看在SQL HAVING子句或只是基於一個子查詢它獲取與此時,相應的MAX值表中的order_id ORDER_ID添加一個WHERE子句。

0
SELECT 
    o.ClientID, 
    o.Date, 
    o.OrderNumber 
FROM dbo.tblOrders o 
INNER JOIN (SELECT 
       o1.ClientId, 
       MAX(o1.Date) as MaxDate, 
       o1.OrderNumber 
      FROM dbo.tblOrders o1 
      GROUP BY o.ClientId) o2 ON o.ClientID = o2.ClientID AND o.Date = o2.MaxDate