Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Advance "distinct" or "group By"

Author  Topic 

khadem1386
Starting Member

1 Post

Posted - 2011-11-08 : 04:44:40
Hi
this is my scenario:
my Table has about 1,000,000 Records that saved During 20 days
when a page load on my page it add a record on DB.

These are my fields . that save Ip Of my visitor.

ID , Date_server , IP

"Date_server" is Date-time DATA TYPE

Now I want count number of my visitors.
so this is my query to count my VISITORs on '3-10-2011'.


SELECT COUNT(distinct ip) AS [Number of visitors]
FROM Table1
where CONVERT(VARCHAR(10),(Date_server), 105) = '3-10-2011'


It return 5700

Then I check by some another counters.
They return 7600

After it I see that problem is "VISITOR" 's Meaning. this is my new rule
-When an Ip(visitor) leave my site for more than 30 minutes. then he return to site , He is a new visitor.
-But if he has not a gap large than 30 minutes. he is not a new visitor for my counter.

What query you offer for me, instead "Distinct"?
or is there any advance "Distinct"?
or can we use advance "Where" or sub-query or "Group by"?

Is there any

I need your code sample please
Thanks for your time

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-08 : 07:09:13
try something like

SELECT ROW_NUMBER() OVER (PARTITION BY ip ORDER BY Date_server ASC) AS Rn, * INTO #Temp
FROM Table1
WHERE Date_server> = '2011-10-03'
AND Date_server < '2011-10-04'

;With Visitors
AS
(
SELECT Rn,Date_server , IP,CAST(IP AS varchar(100)) AS DistVisit
FROM #Temp
WHERE Rn=1
UNION ALL
SELECT t.Rn,t.Date_server,t.IP,CAST(CASE WHEN DATEDIFF(mi,v.Date_server,t.Date_server) > 30 THEN t.IP + CAST(t.Rn AS varchar(10)) ELSE t.IP END AS varchar(100))
FROM Visitors v
INNER JOIN #Temp t
ON t.IP = v.IP
AND t.Rn = v.Rn + 1
)

SELECT COUNT(DISTINCT DistVisit)
FROM Visitors

DROP TABLE #Temp


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -