2017-08-25 85 views
1

我有以下查詢:沒有組聚合列由

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]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'leadbind.leads.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: 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)

是否有可能解決此同時仍保持group by date?我想保留子查詢。

回答

-2

應該

group by date_format(leads.updated_at, "%m/%d/%Y") , leads.id 

集團首先談到選擇之前執行

+0

如果'updated_at'是DATETIME或TIMESTAMP,那麼你的回答是錯誤的。無論如何,它不回答這個問題。 –

+0

再試一次... – maSTAShuFu

+0

現在它解決了這個錯誤,但可能不會給出OP的預期結果。 –

1

的錯誤是常見的一種SQL的層次。它來自有關GROUP BY查詢的規則:您不能讓列產生不明確的結果。您的選擇列表中的所有列必須位於GROUP BY子句中,或位於聚合函數內,否則在功能上依賴於GROUP BY子句中的列。

,詳細瞭解這個規則,閱讀https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

你的子查詢列assignmentsreturns違反了這一規則。每個date有多個id。因此,您希望計算結果的數量是多少?我想你會希望給定日期的所有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)其中EXPR爲空不計行。