SQL查询WHERE问题

时间:2010-09-16 19:59:57

标签: sql sql-server tsql

我有这个针对速度优化的查询(这就是为什么它看起来有点奇怪 - 一段时间得到一些帮助)。

想要确切的结果,但我只想在最后一分钟内获得结果而不是更早。

此查询返回最后100个,无论是什么,而不仅仅是最后一分钟的结果。

SessionGuid不是唯一的 - 实际上它是这个表中多行的关键。

感谢您的帮助

SELECT TOP(@resultCount) * FROM  
( 
    SELECT 
        [UserSessionSequenceID] 
        ,[SessionGuid] 
        ,SiteID
        ,IP
        ,UrlTitle
        ,Url
        ,Referer
        ,[Timestamp] 
        ,ROW_NUMBER() over (
            PARTITION BY [SessionGuid]  
            ORDER BY UserSessionSequenceID DESC) 
         AS sort  
   FROM [tblSequence] 
   where SiteID = @siteID
   and [Timestamp] > DATEADD(mi, -@minutes, (LEFT(GETDATE(),12)))
) AS new
WHERE sort = 1 
and not exists (
    select SessionGuid 
    from tblSequence
    where SiteID = @siteID
    and SessionGuid = new.SessionGuid
    and [TimeStamp] < DATEADD(mi, -@minutes, (LEFT(GETDATE(),12)))
)
ORDER BY [UserSessionSequenceID] DESC

我的表格看起来像这样

CREATE TABLE [dbo].[tblSequence](
    [UserSessionSequenceID] [bigint] IDENTITY(1,1) NOT NULL,
    [IP] [nvarchar](50) NULL,
    [SessionGuid] [nvarchar](50) NOT NULL,
    [Url] [nvarchar](1550) NULL,
    [UrlTitle] [nvarchar](1550) NULL,
    [Cords] [nvarchar](2550) NULL,
    [SiteID] [int] NOT NULL,
    [BrowserWidth] [int] NULL,
    [BrowserHeight] [int] NULL,
    [Browser] [nvarchar](550) NULL,
    [BrowserVersion] [nvarchar](50) NULL,
    [IsCrawler] [bit] NOT NULL,
    [Referer] [nvarchar](1550) NULL,
    [Timestamp] [datetime] NULL
) ON [PRIMARY]

2 个答案:

答案 0 :(得分:3)

我将您的查询重写为:

WITH new AS (
   SELECT [UserSessionSequenceID],
          [SessionGuid],
          SiteID,
          IP,
          UrlTitle,
          Url,
          Referer,
          [Timestamp],
          ROW_NUMBER() OVER (PARTITION BY [SessionGuid]  
                                 ORDER BY UserSessionSequenceID DESC) AS sort  
     FROM [tblSequence] 
    WHERE SiteID = @siteID
      AND [Timestamp] > DATEADD(mi, -@minutes, GETDATE()))
  SELECT TOP(@resultCount) 
         n.* 
    FROM new n
   WHERE n.sort = 1 
     AND NOT EXISTS (SELECT NULL
                     FROM tblSequence s
                    WHERE s.siteid = n.siteid
                      AND s.sessionguid = n.sessionguid
                      AND [TimeStamp] <= DATEADD(mi, -@minutes, GETDATE())
ORDER BY n.usersessionsequenceid DESC

答案 1 :(得分:2)

尝试使用

DATEADD(mi, -@minutes, GETDATE()) 

而不是

DATEADD(mi, -@minutes, (LEFT(GETDATE(),12)))