2013-03-19 166 views
-1
select distinct 
    assignedTo, 
    alert_id, 
    insert_date_time, 
    alert_status_id, 
    alert_action_id, 
    alert_call_reason_id, 
    target_date 
from Case_Management.AlertDetail 

工作正常。(看似)簡單查詢的SQL錯誤

select distinct 
    assignedTo, 
    alert_id, 
    max(insert_date_time), 
    alert_status_id, 
    alert_action_id, 
    alert_call_reason_id, 
    target_date 
from Case_Management.AlertDetail 

返回,因爲它不是在聚合函數或GROUP BY子句中包含的錯誤列「Case_Management.AlertDetail.assignedTo」在選擇列表中無效。

我很難過。

+1

對於其餘字段,您正在使用不帶「GROUP BY」的聚合函數('MAX')。 – LittleBobbyTables 2013-03-19 19:41:54

回答

5

的錯誤是很清楚,在聚合函數添加不列到GROUP BY條款:

select 
    assignedTo, 
    alert_id, 
    max(insert_date_time), 
    alert_status_id, 
    alert_action_id, 
    alert_call_reason_id, 
    target_date 
from Case_Management.AlertDetail 
GROUP BY assignedTo, 
     alert_id, 
     alert_status_id, 
     alert_action_id, 
     alert_call_reason_id, 
     target_date; 
0

您BY子句中的第2個查詢需要一個組,因爲你有一個彙總。總計是

max(insert_date_time) 
0

想想你想達到什麼。您想要選擇一些記錄,但其中一列不是常規記錄的內容,而是所有列的彙總。你無法混合。

您需要對數據進行分組以實現該功能或使用子選擇。