Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE clause inside COUNT(DISTINCT) clause

Tags:

mysql

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.

like image 546
o17t H1H' S'k Avatar asked Aug 01 '11 13:08

o17t H1H' S'k


People also ask

Can you use count distinct in the WHERE clause?

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.

How count distinct values with conditions in SQL?

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];

Can you have count in WHERE clause SQL?

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.

Is NULL counted in count distinct?

NULL values are not included in COUNT DISTINCT counts.


1 Answers

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
like image 168
Bohemian Avatar answered Oct 13 '22 01:10

Bohemian