2014-05-12 53 views
0

我有一個查詢,低於:錯誤使用ORDER BY和GROUP BY一起

SELECT 
    o.ordernum, 
    o.SCHEDATTEMPT, 
    o.lastcontactdate, 
    MAX(OE.NextContactDate) AS NextContactDate 
FROM orderevents OE 
FULL outer join orde_ o 
ON o.ORDERID=oe.OrderId 
WHERE O.lastcontactdate is not null and SCHEDULED is null and DROPTIME is null  
ORDER by O.LASTcontactdate 

當我執行此查詢我得到的錯誤Column 'orde_.ORDERNUM' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

我在這個查詢中做錯了什麼?

+0

@MitchWheat我怎樣才能解決這個 –

回答

3

錯誤消息說明了一切,但如果您看到它,則其含義更易於理解。

在選擇列表中使用聚合函數(即MAX(OE.NextContactDate)),聚合函數需要包含在你的選擇列表中的所有條目...您的選擇列表

SELECT 
    MAX(o.ordernum),  -- technically contained in an aggregate function - setting aside that it's probably not what you want otherwise 
    MAX(o.SCHEDATTEMPT), -- same 
    MAX(o.lastcontactdate), -- same 
    MAX(OE.NextContactDate) AS NextContactDate 
FROM orderevents OE 
FULL outer join orde_ o 
ON o.ORDERID=oe.OrderId 
WHERE O.lastcontactdate is not null and SCHEDULED is null and DROPTIME is null 
ORDER by MAX(o.lastcontactdate) 

... 條目不被聚合函數包含需要在一個GROUP BY條款:

SELECT 
    o.ordernum, 
    o.SCHEDATTEMPT, 
    o.lastcontactdate, 
    MAX(OE.NextContactDate) AS NextContactDate 
FROM orderevents OE 
FULL outer join orde_ o 
ON o.ORDERID=oe.OrderId 
WHERE O.lastcontactdate is not null and SCHEDULED is null and DROPTIME is null 
GROUP BY o.ordernum, o.SCHEDATTEMPT, o.lastcontactdate -- added GROUP BY clause 
ORDER by o.lastcontactdate 

我懷疑你真正想要的第二修復 - 爲GROUP BY條款添加到您的查詢。

+1

當我使用第一次查詢我再次給予同樣的錯誤,味精'列「orde_.LastContactDate」是無效的ORDER BY子句,因爲....' –

+0

@ A.Goutam:良好的漁獲。對於那個很抱歉。是的,當你在一個選擇列表(例如'MAX(o.lastcontactdate)')的集合函數中包裝一列時,該列不能在ORDER BY子句中「解包」(即'o.lastcontactdate')。它必須被包裝在聚合函數中,就像它在選擇列表中一樣。我相應地更新了第一個查詢。 – J0e3gan

+1

@ Joe3gan其作品 –