我有以下查询:
select
count(*) as leads,
(select count(*) from assignments where lead_id=leads.id and deleted_at is null) as assignments,
(select count(*) from assignments where lead_id=leads.id and deleted_at is not null) as returns,
date_format(leads.updated_at, "%m/%d/%Y") as date
from `leads` where leads.updated_at between "2017-08-24 04:00:00" and "2017-08-26 03:59:59"
group by `date`
这会产生以下错误:
SQLSTATE [42000]:语法错误或访问冲突:1055表达式#2 SELECT列表不在GROUP BY子句中并包含nonaggregated 列'leadbind.leads.id'在功能上不依赖于 GROUP BY子句中的列;这是不相容的 sql_mode = only_full_group_by(SQL:选择count()作为引导,(选择 从分配中计算(),其中lead_id = leads.id和deleted_at是 null)作为赋值,(从赋值中选择count(*)) lead_id = leads.id和deleted_at不为null)作为返回, date_format(leads.updated_at,“%m /%d /%Y”)作为
leads
的日期 “2017-08-24 04:00:00”和“2017-08-26”之间的leads.updated_at 03:59:59“分组date
)
是否可以在保持group by date
的同时更正此问题?我想保留子查询。
答案 0 :(得分:1)
错误是常见错误。它来自关于GROUP BY查询的规则:您不能让列产生模糊结果。 select-list中的所有列必须位于GROUP BY子句中,或者位于聚合函数内,或者在功能上依赖于GROUP BY子句中的列。
有关此规则的详细信息,请阅读https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
您的子查询列returns
和id
违反了此规则。每date
有多个id
。因此,您希望计算结果的分配和返回数量是多少?我猜你想要在给定日期内所有select
count(*) as leads,
SUM((select count(*) from assignments where lead_id=leads.id and deleted_at is null)) as assignments,
SUM((select count(*) from assignments where lead_id=leads.id and deleted_at is not null)) as returns,
date_format(leads.updated_at, '%m/%d/%Y') as date
from `leads`
where leads.updated_at between '2017-08-24 04:00:00' and '2017-08-26 03:59:59'
group by `date`
值的总分配和回报。
select
count(*) as leads,
COUNT(CASE WHEN a.deleted_at is null THEN a.lead_id END)) as assignments,
COUNT(CASE WHEN a.deleted_at is not null THEN a.lead_id END)) as returns,
date_format(leads.updated_at, '%m/%d/%Y') as date
from `leads` as l
left outer join `assignments` as a on l.id = a.lead_id
where leads.updated_at between '2017-08-24 04:00:00' and '2017-08-26 03:59:59'
group by `date`
我将字符串分隔符更改为更加标准的单引号。
我会进一步使用连接编写此查询,而不是执行两个相关的子查询:
COUNT(expr)
{{1}}不计算 expr 为空的行。
答案 1 :(得分:-2)
应该是
group by date_format(leads.updated_at, "%m/%d/%Y") , leads.id
在执行sql层次结构
中选择之前,分组依次排在第一位