SQL min和max返回不同的结果集

时间:2017-12-01 23:40:32

标签: sql sql-server-2012 max min

我正在尝试提取单个会话ID的最小和最大时间戳来进行一些分析。 什么可能导致相同SQL查询的MIN和MAX版本返回(稍微)不同的结果集?我很困惑为什么我得到不同数量的结果。数据库未实时更新。有没有人有可能的言论?

SELECT [ActivityLogs].sessionid,
       maxSelect.mxDate,
       [ActivityLogs].ClientIp INTO ##maxSessionTimes
FROM [OLBRET_COPY].[dbo].[ActivityLogs]
INNER JOIN
  (SELECT max([ActivityLogs].[DateTime]) mxDate,
          SessionId
   FROM [OLBRET_COPY].[dbo].[ActivityLogs]
   GROUP BY SessionId) maxSelect ON [ActivityLogs].SessionId = maxSelect.SessionId
AND [ActivityLogs].[DateTime] = maxSelect.mxDate
WHERE [ActivityLogs].[DateTime] > '2017-11-29'


SELECT [ActivityLogs].sessionid,
       minSelect.mxDate,
       [ActivityLogs].ClientIp INTO ##minSessionTimes
FROM [OLBRET_COPY].[dbo].[ActivityLogs]
INNER JOIN
  (SELECT min([ActivityLogs].[DateTime]) mxDate,
          SessionId
   FROM [OLBRET_COPY].[dbo].[ActivityLogs]
   GROUP BY SessionId) minSelect ON [ActivityLogs].SessionId = minSelect.SessionId
AND [ActivityLogs].[DateTime] = minSelect.mxDate
WHERE [ActivityLogs].[DateTime] > '2017-11-29'

1 个答案:

答案 0 :(得分:0)

我建议您使用min / max作为窗口函数,这样您就可以使用单个查询:

SELECT
        *
FROM (
      SELECT
              *
            , MIN([DateTime]) over(partition by sessionid) minDateTime
            , MAX([DateTime]) over(partition by sessionid) maxDateTime
      FROM [OLBRET_COPY].[dbo].[ActivityLogs]
      WHERE [ActivityLogs].[DateTime] > '2017-11-29'
      ) d
WHERE [DateTime] = minDateTime or [DateTime] = maxDateTime