1

我遵循了这个网站上关于从一组行中选择 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
4

3 回答 3

1

MAXDATETIME数据类型上显然要考虑时间,这不是您的查询有什么问题。问题是您不能确保 for 的最大值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
于 2013-01-15T12:46:48.597 回答
0

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

SQLFIDDLE示例

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 |

查询是否有相同日期的相同项目号:

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
于 2013-01-16T07:30:13.183 回答
0

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

例如。添加您的数据 (4, 'On Time', '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
              )
于 2013-01-19T13:07:12.727 回答