开发者

SQL query WHERE problem

I have this query that is optimized for speed (that's why it might look a bit odd - got some help a while back).

Want the exact result as this BUT I ONLY want results from within the LAST minute not older.

This query returns the last 100 no matter what and not only results from the last minute.

SessionGuid is not unique - in fact it's sort of a key on multiple rows in this table.

Thanks for the help

SELECT TOP(@resultCount) * FROM  
( 
    SELECT 
        [UserSessionSequenceID] 
        ,[SessionGuid] 
        ,SiteID
        ,IP
        ,UrlTitle
        ,Url
        ,Referer
        ,1673882484 
        ,ROW_NUMBER() over (
            PARTITION BY [SessionGuid]  
            ORDER BY UserSessionSequenceID DESC) 
         AS sort  
   FROM [tblSequence] 
   where SiteID = @siteID
   and 1673882484 > 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

My table looks like this

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,
    1673882484 [datetime] NULL
) ON [PRIMAR开发者_如何学GoY]


I re-wrote your query as:

WITH new AS (
   SELECT [UserSessionSequenceID],
          [SessionGuid],
          SiteID,
          IP,
          UrlTitle,
          Url,
          Referer,
          1673882484,
          ROW_NUMBER() OVER (PARTITION BY [SessionGuid]  
                                 ORDER BY UserSessionSequenceID DESC) AS sort  
     FROM [tblSequence] 
    WHERE SiteID = @siteID
      AND 1673882484 > 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


Try using

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

instead of

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜