COUNT(DISTINCT)子句中的WHERE子句

eya*_*ler 11 mysql

这是Ryan Frank在forums.mysql.com上提出的问题,我也面临这个问题.

我在SELECT语句的开头有以下内容:

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
Run Code Online (Sandbox Code Playgroud)

这将返回我需要的所有变量; 但是,我想将使用COUNT(DISTINCT)的变量限制为日期范围.我不能在FROM子句后使用WHERE子句.例如:

FROM accounts
WHERE accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to'
Run Code Online (Sandbox Code Playgroud)

不会工作,因为它不会给我所有帐户,就像我需要的那样.

我正在寻找类似的东西:

COUNT(DISTINCT accounts_log.login_time WHERE accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to') AS visits
Run Code Online (Sandbox Code Playgroud)

PS我知道上面的内容不起作用,并且已经用完了语法选项.

Boh*_*ian 12

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
Run Code Online (Sandbox Code Playgroud)