简单的MS SQL计数问题

时间:2010-08-03 13:05:16

标签: sql sql-server tsql

我有这个SQL

DECLARE @url varchar(100)
SET @url = 'http://mysite.com/%'

SELECT
[UserSessionSequenceID]
      ,[SiteID]
      ,[Referer]
      ,[Timestamp]
,ROW_NUMBER() over (PARTITION BY [Referer] ORDER BY referer DESC) AS sort 
  FROM [tblSequence]
WHERE [Referer] IS NOT NULL AND [Referer] NOT LIKE @url AND siteID = 15

想要计算唯一的引用 - 问题是这个SQL返回所有匹配并逐个计算。 我只想要每个唯一引用者的计数(并且仍然将@url排除在外)。

怎么做?

3 个答案:

答案 0 :(得分:3)

SELECT
      [Referer], Count([Referer]) as RefCount
  FROM [tblSequence]
WHERE [Referer] IS NOT NULL AND [Referer] NOT LIKE @url AND siteID = 15
GROUP BY [Referer]

重新下订单(如果真的需要)取决于您的确切要求。

答案 1 :(得分:3)

如果您需要行数据而不是聚合

,请使用DENSE_RANK not ROW_NUMBER

答案 2 :(得分:0)

 DECLARE @url varchar(100)
 SET @url = 'http://example.com/%'

  SELECT
  distinct [UserSessionSequenceID]
  ,[SiteID]
  ,[Referer]
  ,[Timestamp]
 ,count(*) over (PARTITION BY [Referer] ORDER BY referer DESC) AS sort 
  FROM [tblSequence]
  WHERE [Referer] IS NOT NULL AND [Referer] NOT LIKE @url AND siteID = 15