查询初始记录集的最大日期时间

时间:2014-10-03 17:01:07

标签: sql-server vb.net tsql

我试图在MS SQL数据库中查询基于两个参数的记录集。一个是GUID,另一个是日期时间字段,我不知道结果集中的最大日期时间值或记录数。

SELECT        ID, code, txtString, msgGUID, tcStat, reportDT
FROM            tblCodes
WHERE        (msgGUID = @msgGUID) AND ....

如何查询此初始集的最大日期时间值,并仅返回reportDT日期时间值的最新记录?就像在WHERE子句中使用MAX来获取reportDT值一样。

我将此应用于vb.net app SQL数据源。

4 个答案:

答案 0 :(得分:1)

  SELECT        ID, code, txtString, msgGUID, tcStat, reportDT FROM   tblCodes 
  WHERE      msgGUID = @msgGUID AND ... AND   reportDT = ( SELECT MAX(reportDT) FROM tblCodes where (msgGUID = @msgGUID) AND ... )

答案 1 :(得分:1)

SELECT top (1) with ties
  ID, code, txtString, msgGUID, tcStat, reportDT
FROM            tblCodes
WHERE        (msgGUID = @msgGUID) AND ....
order by reportDT desc;

如果您需要一整天的所有记录(即时间部分无关紧要),您可以将该字段转换为date部分中的order by数据类型。

答案 2 :(得分:0)

您可以使用CTE执行此操作,以获得完整的日期/时间匹配:

;WITH FullSubSet AS (
        SELECT ID, code, txtString, msgGUID, tcStat, reportDT
        FROM tblCodes
        WHERE (msgGUID = @msgGUID) AND ....),

      MaxDateVal AS (
        SELECT MAX(reportDT) AS reportDT FROM FullSubSet)

SELECT ID, code, txtString, msgGUID, tcStat, reportDT
FROM FullSubSet X
WHERE X.reportDT = (SELECT reportDT FROM MaxDateVal)

或者抛出时间戳(SQL2008 +),如下所示:

;WITH FullSubSet AS (
        SELECT ID, code, txtString, msgGUID, tcStat, reportDT
        FROM tblCodes
        WHERE (msgGUID = @msgGUID) AND ....),

      MaxDateVal AS (
        SELECT CONVERT(DATE,MAX(reportDT)) AS reportDT FROM FullSubSet)

SELECT ID, code, txtString, msgGUID, tcStat, reportDT
FROM FullSubSet X
WHERE X.reportDT >= (SELECT reportDT FROM MaxDateVal)

非CTE版本:

SELECT ID, code, txtString, msgGUID, tcStat, reportDT
FROM tblCodes 
WHERE (msgGUID = @msgGUID) AND ....
AND reportDT = (SELECT MAX(reportDT) AS reportDT
                FROM tblCodes 
                WHERE (msgGUID = @msgGUID) AND ....)

答案 3 :(得分:0)

SELECT   top 1      
         ID, code, txtString, msgGUID, tcStat, reportDT
FROM     tblCodes
WHERE    msgGUID = @msgGUID 
ORDER BY reportDT desc