MAX on group返回具有相同日期但不同时间的多个值

时间:2013-01-15 10:42:27

标签: sql sql-server sql-server-2005 max

我已经关注了本网站上关于从一组行中选择MAX的许多优秀建议。

我有一个历史档案,我只想要每个项目编号的最新日期和评论。我正在从这个信息中创建一个Boxi世界中的派生表。这一切都很顺利,但如果同一天有两个条目,但有不同的时间,它们都会被退回。这会在后续报告中复制该条目。有没有办法让MAX命令下降到日期字段的时间级别?

数据库是SQL Server 2005

-------------用于派生表的SQL

Select
   Projectno, Comment, CreatedOn
from 
   ReportHistory
Where
   ReportHistory.ItemName=('ProjectCode1')
and
   CreatedOn in(Select max(CreatedOn) FROM ReportHistory group by Projectno)

-------------------示例数据库

Projectno     Comment             Created on

1             Started             2013-01-04 11:04:00
2             Late                2013-01-06 11:22:00
3             Late                2013-01-07 11:06:00
1             On Time             2013-01-08 11:01:00   *these two both get selected*
1             Late                2013-01-08 12:05:00   *these two both get selected*
3             Back on schedule    2013-01-08 14:20:00
2             Still overdue       2013-01-09 09:01:00

3 个答案:

答案 0 :(得分:1)

MAX数据类型上的

DATETIME显然需要考虑时间,这不是您的查询有什么问题。问题是您无法确保CreatedOn的最大值是针对正确的ProjectNo。您可以使用分析函数:

;WITH CTE AS
(
    SELECT  Projectno, 
            Comment, 
            CreatedOn,
            ROW_NUMBER() OVER(PARTITION BY ProjectNo ORDER BY CreatedOn DESC) RN
    FROM ReportHistory
    WHERE ReportHistory.ItemName = 'ProjectCode1'
)
SELECT Projectno, Comment, CreatedOn
FROM CTE
WHERE RN = 1

答案 1 :(得分:0)

查询是否没有相同的projectno具有相同的日期:

<强> SQLFIDDLEExample

SELECT h.Projectno,
       h.Comment,
       h.[Created on]
FROM ReportHistory h
WHERE h.[Created on] =(Select max(h2.[Created on])
                       FROM ReportHistory h2 
                       WHERE h2.Projectno = h.Projectno )
ORDER BY h.Projectno

结果:

| PROJECTNO |          COMMENT |                     CREATED ON |
-----------------------------------------------------------------
|         1 |             Late | January, 08 2013 12:05:00+0000 |
|         2 |    Still overdue | January, 09 2013 09:01:00+0000 |
|         3 | Back on schedule | January, 08 2013 14:20:00+0000 |

查询是否存在具有相同日期的同一projectno:

SELECT h.Projectno,
       MAX(h.Comment) AS Comment,
       h.[Created on]
FROM ReportHistory h
WHERE h.[Created on] =(Select max(h2.[Created on])
                       FROM ReportHistory h2 
                       WHERE h2.Projectno = h.Projectno )
GROUP BY h.Projectno,
       h.[Created on]
ORDER BY h.Projectno

答案 2 :(得分:0)

我认为当不同项目的日期相同时,您会收到副本。

例如。添加您的数据(4,'准时','2013-01-08 11:01:00')                                                                                                            然后结果将是SQLFiddle

但是你需要这个结果SQLFiddle

SELECT *
FROM ReportHistory t
WHERE t.ItemName=('ProjectCode1')
  AND EXISTS (
              SELECT 1
              FROM ReportHistory                              
              WHERE projectNo = t.projectNo
              GROUP BY projectNo
              HAVING MAX(CreatedOn) = t.CreatedOn
              )