T-SQL:如何根据最大日期选择行?

时间:2016-06-17 09:24:52

标签: sql sql-server tsql greatest-n-per-group

我有一个表,其中有两个字段,我想做出决定:

- DATE
- DATE_LOADED

我想知道是否有DATE(可能有很多关联的行),比如说“2016-06-15”,它有两个唯一的DATE_LOADED条目,'2016-06-16''2016-06-17',然后只使用MAX DATE_LOADED行。

实际上,有两份报告报告了同一天的重叠数据。后来的报道是一个修正。所有列都可能已更新但DATE。

ASK:
 对于每个DATE(不只是每个单独的行),检查是否存在多个DATE_LOADED,如果存在,那么将与该DATE相关联的所有行以及该特定日期的DATE_LOADED = MAX DATE_LOADED。< / p>

4 个答案:

答案 0 :(得分:4)

这可以使用窗口函数

来完成
select *
from (
   select t.*, 
          row_number() over (partition by date order by date_loaded desc) as rn
   from the_table t
) x
where rn = 1;

如果有多个行具有相同的最大日期,则上述只会返回其中一个。如果你想要所有,你可以使用这样的东西:

select *
from (
   select t.*, 
          max(date_loaded) over (partition by date) as max_date_loaded
   from the_table t
) x
where date_loaded = max_date_loaded;

如果您只想使用一个DATE_LOADED过滤掉DATE,则可以将查询增强到:

select *
from (
   select t.*, 
          max(date_loaded) over (partition by date) as max_date_loaded,
          count(*) over (partition by date) as cnt
   from the_table t
) x
where date_loaded = max_date_loaded
  and cnt > 1;

答案 1 :(得分:3)

此查询将为您提供DATE的列表,该日期的不同DATE_LOADED值的总数以及这些记录中的最大DATE_LOADED值。

SELECT DATE
   , COUNT(DISTINCT DATE_LOADED) AS [Total Different DATE_LOADED Values]
   , MAX(DATE_LOADED) AS [Max DATE_LOADED]
FROM YOURTABLE
GROUP BY DATE
HAVING COUNT(DISTINCT DATE_LOADED) > 1

我后来看到了

  

然后获取与该DATE相关联的所有行以及该特定日期的DATE_LOADED = MAX DATE_LOADED。

这可以通过将上面的查询加入到您的表中来实现。这将产生原始表中与先前查询匹配的所有记录的结果。

SELECT yt.* 
FROM YOURTABLE AS yt INNER JOIN
    (SELECT DATE
       , MAX(DATE_LOADED) AS [Max DATE_LOADED]
    FROM YOURTABLE
    GROUP BY DATE
    HAVING COUNT(DISTINCT DATE_LOADED) > 1
    ) AS subQry ON yt.DATE = subQry.DATE AND yt.DATE_LOADED = subQry.[Max DATE_LOADED]

答案 2 :(得分:1)

您可以使用CROSS APPLY或INNER JOIN来实现此目的。以下是CROSS APPLY的示例。

SELECT  t.[DATE],
        t.DATE_LOADED    
FROM YourTable t
CROSS APPLY (
    SELECT MAX(DATE_LOADED) as MAX_DATE_LOADED 
    FROM YourTable 
    WHERE [DATE] = t.[DATE]) as p
WHERE t.DATE_LOADED = p.MAX_DATE_LOADED

例如,如果在您的表格中有以下内容:

DATE        DATE_LOADED
2016-06-15  2016-06-16
2016-06-15  2016-06-17
2016-06-15  2016-06-18
2016-06-15  2016-06-18

以上查询将为您提供:

DATE        DATE_LOADED
2016-06-15  2016-06-18
2016-06-15  2016-06-18

答案 3 :(得分:0)

我相信你是在追求下面的事情

Select Date,MAX(DateLoaded)
From TableName    
Group By Date