首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WHERE子句COUNT(DISTINCT)子句内部

WHERE子句COUNT(DISTINCT)子句内部
EN

Stack Overflow用户
提问于 2011-08-01 21:28:00
回答 2查看 15.3K关注 0票数 12

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

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

代码语言:javascript
复制
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

这将返回我需要的所有变量;但是,我希望将使用COUNT(DISTINCT)的变量限制在一个日期范围内。我不能在FROM子句之后使用WHERE子句。例如:

代码语言:javascript
复制
FROM accounts
WHERE accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to'

不会起作用,因为它不会给我需要的所有帐户。

我正在寻找类似这样的东西:

代码语言:javascript
复制
COUNT(DISTINCT accounts_log.login_time WHERE accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to') AS visits

附言:我知道上面的方法不起作用,语法选项已经用完了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-08-01 21:34:15

代码语言:javascript
复制
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
票数 13
EN

Stack Overflow用户

发布于 2011-08-01 21:35:45

您可以将条件放在LEFT JOINON子句中:

代码语言:javascript
复制
 SELECT a.id, a.company, a.first, a.last,
 COUNT(DISTINCT al.login_time) AS visits
 FROM accounts a
 LEFT JOIN accounts_log al ON (al.account_id = a.id AND 
 al.login_time BETWEEN '$search_from' AND '$search_to')

其他表也是如此。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6899085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档