Question

I have two columns in a table: VisitorID, and URL.

An entry exists in the table for every page view a visitor makes. I'd like to see the total number of visits for each Visitor, where NONE of the URLs in a visitor's group are LIKE "%page=checkout%".

I'm thinking it's something like this:

SELECT *, COUNT(*) AS TotalVisits
FROM `VisitorLog`
GROUP BY VisitorID
HAVING `URL` NOT IN (SELECT * FROM ?? WHERE `URL` LIKE "%page=checkout%")

But I don't entirely understand how the HAVING clause works with a sub-query, if I need a sub-query at all, etc? And how to make having negative?

And bonus points for anyone who can explain the answer so that I can do it myself next time!

Thanks,

Nick

Was it helpful?

Solution

SELECT *, COUNT(*) AS TotalVisits
FROM `VisitorLog`
WHERE 
    VisitorID NOT IN 
        (SELECT VisitorID FROM `VisitorLog` WHERE `URL` LIKE '%page=checkout%')
GROUP BY VisitorID

OTHER TIPS

select VisitorID, count(*)
from VisitorLog
where (select count(*) from VisitorLog v2 where v2.VisitorID = VisitorLog.VisitorID and v2.URL like '%page=checkout%') = 0
;

I assume your URL field in visitorLog table is foreign_key and integer field.

SELECT v1.VisitorID, COUNT(v1.VisitorID) AS TotalVisits
FROM `VisitorLog` v1, ?? as v2
WHERE v1.URL = v2.URL_ID
AND v2.URL NOT LIKE "%page=checkout%"
GROUP BY VisitorID

As from my understanding,eg.

id      visitor_id    datetime    page
1       1             Nov4        about us
2       1             Nov4        contact us
3       2             Nov4        about us
4       2             Nov3        about us
5       2             Nov4        home
6       1             Nov4        home


    select visitor_id, count(id) as numberofvisits 
    FROM visit_table_transaction 
    WHERE datetime = "Nov4"
    GROUP BY visitor_id
    HAVING numberofvisits > 2

So the result is 
visitor_id      numberofvisits
1               3

Why you need to use having, because aggregate function can't be use in WHERE

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

You can also write like this

select visitor_id, count(id) as numberofvisits 
FROM visit_table_transaction 
WHERE datetime = "Nov4"
GROUP BY visitor_id
HAVING count(id) > 2

Below is wrong

 select visitor_id, count(id) as numberofvisits 
 FROM visit_table_transaction 
 WHERE datetime = "Nov4"
 AND count(id) > 2
 GROUP BY visitor_id 

Any one please correct me if I am wrong. Thanks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top