SQL最近的行

时间:2016-02-17 15:46:40

标签: sql date join max

对此有点困难..我正在尝试根据地区和产品获取最新记录。

我试过了:

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

2 个答案:

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

您的版本也应该有用。如果没有,则可能是由于日期格式。您是否使用原生日期/时间格式存储日期?或者,您使用的是不合适的格式,例如字符串吗?

答案 1 :(得分:0)

抱歉,原件不包含Type = 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