0
SELECT numTimesIndexLoaded, numTimesIndexLoadedUnique, numTimesResultsLoaded, numTimesResultsLoadedUnique, numTimesCTALoaded, numTimesCTALoadedUnique
FROM
(SELECT
sum(ctaSL.page = 'index') AS numTimesIndexLoaded,
sum(ctaSL.page = 'results') AS numTimesResultsLoaded,
sum(ctaSL.page = 'cta') AS numTimesCTALoaded,
count(distinct ctaSL.ip_address, ctaSL.page = 'index') AS numTimesIndexLoadedUnique,
count(distinct ctaSL.ip_address, ctaSL.page = 'results') AS numTimesResultsLoadedUnique,
count(distinct ctaSL.ip_address, ctaSL.page = 'cta') AS numTimesCTALoadedUnique
FROM
stats_page_loads AS ctaSL
WHERE ctaSL.campaign_id = ?
    AND ctaSL.mode = ?
) t1

I have the following prepared statement where I'm trying to get stats for a web page. The goal is to have both the stats of how many times each of the three pages is load, but also how many times it's loaded by a unique IP address for each of the three pages. I'm new to using distinct, so not even sure if it's the right thing to use, but I'm not getting the proper result so I'm assuming I'm using it wrong.

I figured I could just make another SELECT statement as t2, but trying to avoid that since I'll have to add the ? variables over and over again the more I add to it, so was hoping to have it condensed into one, if possible.

2
  • 1
    See the following guidance how to ask a good sql related question: meta.stackoverflow.com/questions/333952/… This question as it stansd is unanswerable because the key is within the data. Commented Jan 17, 2017 at 20:49
  • As a hint for you, start with reading about GROUP BY Commented Jan 17, 2017 at 20:52

1 Answer 1

1

Try:

count(DISTINCT CASE WHEN ctaSL.page = 'index' THEN ctaSL.ip_address END) AS numTimesIndexLoadedUnique,

and similarly for the other cases. This works because CASE returns NULL if none of the WHEN clauses are matched, and COUNT doesn't count NULL.

Your attempt didn't work because the tests simply return 0 or 1 depending on whether they succeed, and you're just counting all the distinct combinations of the IP and that boolean. It doesn't exclude the rows where the condition fails.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly, and thank you for the explanation. Very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.