2016-02-17 89 views
1

對此有點困難..我試圖根據區域和產品獲取最新記錄。SQL最近行

我已經試過:

SELECT T.Region, 
     T.Product, 
     T.Date, 
     T.Revenue, 
     T.Cost, 
FROM Table as T  
Inner Join (
    Select Region, 
      Product, 
      Max(Date) as Date 
    FROM Table 
    Group By Region, Product) as X 
    On T.Product = X.Product 
And T.Region = X.Region 
And T.Date = X.Date 

表:

Region Product Date  Revenue Cost 
A  X  10/1/2015 21967 0 
A  X  1/31/2016 19935 19935 
A  Z  1/1/1987 20356 0 
A  Z  10/1/1994 20356 0 
B  X  1/31/2016 19942 19942 
B  X  2/1/2016 21238 0 
B  Z  1/1/2004 19942 0 
B  Z  10/1/2014 19942 0 
C  Z  1/1/1987 20354 0 
C  Z  4/1/2002 21972 0 
C  Z  1/31/2016 21972 21972 

期望的結果:

Region Product Date  Revenue Cost 
A  X  1/31/2016 19935 19935 
A  Z  10/1/1994 20356 0 
B  X  2/1/2016 21238 0 
B  Z  10/1/2014 19942 0 
C  Z  1/31/2016 21972 21972 
+0

您面臨的問題是什麼?你使用的是哪個數據庫? –

+0

您當前的查詢有什麼問題? – jarlh

回答

0

雖然你的方法能正常工作,這是ANSI標準row_number()容易得多功能:

SELECT T.Region, T.Product, T.Date, T.Revenue, T.Cost, 
FROM (SELECT t.*, 
      ROW_NUMBER() OVER (PARTITION BY Region, Product ORDER BY Date DESC) as seqnum 
     FROM Table t 
    ) t 
WHERE seqnum = 1; 

您的版本也應該工作。如果沒有,可能是由於日期格式。您是否使用原生日期/時間格式存儲日期?或者,你是否使用了不恰當的格式,如字符串?

0

對不起,原始未包括過濾器,其中類型= 1

Region Product Date  Revenue Cost Type 
A  X  10/1/2015 21967 0  1 
A  X  1/31/2016 19935 19935 0 
A  Z  1/1/1987 20356 0  1 
A  Z  10/1/1994 20356 0  0 
B  X  1/31/2016 19942 19942 1 
B  X  2/1/2016 21238 0  0 
B  Z  1/1/2004 19942 0  1 
B  Z  10/1/2014 19942 0  0 
C  Z  1/1/1987 20354 0  1 
C  Z  4/1/2002 21972 0  0 
C  Z  1/31/2016 21972 21972 1 

該查詢似乎仍然拿起最大日期無論類型,而不是過濾的其中Type = 1

SELECT T.Region, 
     T.Product, 
     T.Date, 
     T.Type, 
     T.Revenue, 
     T.Cost, 
FROM Table as T  
Inner Join (
    Select Region, 
      Product, 
      Type, 
      Max(Date) as Date 
    FROM Table 
    Group By Region, Product, Type) as X 
    On T.Product = X.Product 
And T.Region = X.Region 
And T.Date = X.Date 
And T.Type = X.Type 
WHERE T.Type = 1