使用ORDER BY和GROUP BY一起出错

时间:2014-05-12 05:24:12

标签: sql-server-2008 group-by sql-order-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.

我在这个查询中做错了什么?

1 个答案:

答案 0 :(得分: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子句。