this is a question asked by Ryan Frank on forums.mysql.com, which i am facing as well.
I have the following in the beginning of my SELECT statement:
SELECT accounts.id, accounts.company, accounts.first, accounts.last,
COUNT(DISTINCT accounts_log.login_time) AS visits,
COUNT(DISTINCT accounts_log.ip_address) AS visitors,
COUNT(DISTINCT documents_log.access_time) AS docs,
MAX(accounts_log.login_time) AS login_time
FROM accounts
This returns all of the variables I need; however, I want to limit the variables that use COUNT(DISTINCT) to a date range. I can’t use the WHERE clause after the FROM clause. For example:
FROM accounts
WHERE accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to'
wouldn’t work because it wouldn’t give me ALL accounts like I need.
I’m looking for something like:
COUNT(DISTINCT accounts_log.login_time WHERE accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to') AS visits
P.S. I know the above doesn’t work and have run out of syntax options.
If you try to use COUNT in the WHERE clause, SQL will throw an exception. You can only use an aggregate function if it is within a sub-query contained in a HAVING clause or a select list.
Count Function with DISTINCT keyword. The DISTINCT keyword with the COUNT function in the SELECT query displays the number of unique data of the field from the table. The Syntax of Count Function With DISTINCT keyword is given below: SELECT COUNT(DISTINCT (Column_Name) FROM table_name WHERE [condition];
1. SQL SELECT COUNT with WHERE clause. SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.
NULL values are not included in COUNT DISTINCT counts.
SELECT accounts.id, accounts.company, accounts.first, accounts.last,
COUNT(DISTINCT case when accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to' then accounts_log.login_time else null end) AS visits,
COUNT(DISTINCT case when accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to' then accounts_log.ip_address else null end) AS visitors,
COUNT(DISTINCT case when accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to' then documents_log.access_time else null end) AS docs,
MAX(accounts_log.login_time) AS login_time
FROM accounts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With