使用MAX带来最新记录的问题(日期)

时间:2015-07-31 15:07:21

标签: sql-server-2008 date max

所以我以前没有发生这种情况,并且对MAX函数非常熟悉。我的结果集仍然显示某些值的重复项,但不会显示其他值。

A

ID  Height       DateTimePerformed
1   {170.18|67}  9/14/2013
1   {170.18|67}  9/12/2013
1   {170.18|67}  9/13/2013
2   {182.88|72}  1/13/2014
2   {182.88|72}  9/30/2013
2   {1889.76|744}    9/1/2013
2   {182.88|72} 10/21/2013
2   {182.88|72}  1/20/2014
2   {182.88|72}   3/3/2014
2   {182.88|72}  1/27/2014
2   {182.88|72}   2/3/2014
2   {182.88|72}  2/10/2014
2   {182.88|72}  12/2/2013
2   {182.88|72}   9/4/2013
2   {182.88|72} 11/18/2013
2   {182.88|72}  9/16/2013
2   {182.88|72}  10/7/2013
2   {182.88|72} 12/23/2013
2   {182.88|72}  2/17/2014

查询/说明:

SELECT
*
FROM A
 JOIN (
    SELECT VisitID,Height,MAX(DateTimePerformed) AS 'MaxDateTimePerformed'
    FROM A
    GROUP BY VisitID,Height
    ) AS B
        ON A.VisitID=B.VisitID
            AND A.DateTimePerformed=B.MaxDateTimePerformed

结果:

ID  Height          DateTimePerformed
1   {170.18|67}     9/14/2013
2   {1889.76|744}   9/1/2013
2   {182.88|72}     3/3/2014

4 个答案:

答案 0 :(得分:0)

如果您想要的结果是:

VisitID Height      DateTimePerformed
2       {182.88|72} 2014-03-03
1       {170.18|67} 2013-09-14

然后您需要做的就是从派生表中的select和group by子句中删除height

SELECT 
    A.*
FROM 
    A
JOIN (
    SELECT VisitID,MAX(DateTimePerformed) AS 'MaxDateTimePerformed'
    FROM A
    GROUP BY VisitID
) AS B
  ON A.VisitID=B.VisitID
 AND A.DateTimePerformed=B.MaxDateTimePerformed;

答案 1 :(得分:0)

它是这样的: 如果你查询

SELECT Height, MAX(DateTimePerformed) AS 'MaxDateTimePerformed'

然后您将获得查询中的最高日期值。它将返回一行。

如果您查询

SELECT VisitID,Height,MAX(DateTimePerformed) AS 'MaxDateTimePerformed'

您将获得每个高度的最高日期值,但是通过添加和按TripID分组,您将获得为每个唯一的VisitID返回的行(您通过VisitID进行分组 - 因此一个) - 因此不同的高度行与相同的VisitID将在同一个VisitID下返回唯一身高的数量。

您需要一个子查询来获取与一列相比的最大日期值,然后通过自我加入外部查询中子查询的结果来使用这些值。

答案 2 :(得分:0)

I have created a SqlFiddle for you

public class PropertyBasedResolver : IValueResolver
{
     public PropertyInfo Property { get; set; }

     public PropertyBasedResolver(PropertyInfo property)
     {
          this.Property = property;
     }

     public ResolutionResult Resolve(ResolutionResult source)
     {
           var result = GetValueFromKey(property, source.Value); // gets from some static cache or dictionary elsewhere in your code by reading the prop info and then using that to look up the value based on the key as appropriate
           return source.New(result)
     }
}

答案 3 :(得分:0)

通过使用ORDER BY,您可以使用分析函数ROW_NUMBER()通过特定的MAX / MIN条件仅为每个id选择一行。例如:

SELECT B.* FROM
   (
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateTimePerformed DESC) AS RN, a.* 
    FROM A a
   ) AS B
WHERE B.RN=1
 Order by B.ID ASC

在此示例中,您只有一条记录,其中包含每个ID的最大日期。如果同一个ID具有相同日期的多个记录,则只返回一个。

此外,您可以在OVER子句中指定ORDER BY DateTimePerformed DESC,Height DESC来选择具有DateTimePerformed和Height两者的最大记录。

Sqlfiddle