(使用join)我没有包含在聚合函数或GROUP BY错误中

时间:2009-07-14 16:36:46

标签: sql sql-server

我收到以下错误。

[Microsoft] [ODBC SQL Server驱动程序] [SQL Server]列'STATS.VisitorIP'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我在两个选择列表中都使用了VISITORIP列。我在其中一个中使用了GROUP BY子句,所以我给它添加了VISITORIP。但是我没有在其他选择中使用GROUP BY子句,所以没有添加它。为什么我收到此错误?

SELECT S.VISITORIP, S.HTTPADDRESS, S.DATEENTERED
FROM STATS S
JOIN (SELECT S1.VISITORIP, MAX(S1.DATEENTERED) FROM STATS S1 WHERE DATEENTERED BETWEEN '" & OnlineTime & "' AND '" & NOW() & "') S1
ON S.VISITORIP = S1.VISITORIP AND S.DATEENTERED = S1.DATEENTERED
WHERE S.DATEENTERED BETWEEN '" &TIME& "' AND '" & NOW() & "'
GROUP BY S.VISITORIP, S.HTTPADDRESS, S.DATEENTERED
ORDER BY S.DATEENTERED DESC  

4 个答案:

答案 0 :(得分:5)

您需要嵌套子查询中的GROUP BY,因为您正在尝试为每个VISITORIP获取MAX DATEENTERED。 VISITORIP存在于该子查询的SELECT中,因此您还需要GROUP BY,以便它返回每个访问者的最新日期。

SELECT S.VISITORIP, S.HTTPADDRESS, S.DATEENTERED
FROM STATS S
JOIN (SELECT S1.VISITORIP, MAX(S1.DATEENTERED) FROM STATS S1 WHERE DATEENTERED BETWEEN '" & OnlineTime & "' AND '" & NOW() & "' GROUP BY S1.VISITORIP) S1
ON S.VISITORIP = S1.VISITORIP AND S.DATEENTERED = S1.DATEENTERED
WHERE S.DATEENTERED BETWEEN '" &TIME& "' AND '" & NOW() & "'
GROUP BY S.VISITORIP, S.HTTPADDRESS, S.DATEENTERED
ORDER BY S.DATEENTERED DESC

答案 1 :(得分:1)

此(嵌套查询)无效:

SELECT S1.VISITORIP, MAX(S1.DATEENTERED)
FROM STATS S1 
WHERE DATEENTERED BETWEEN '" & OnlineTime & "' AND '" & NOW() & "'

应该是:

SELECT S1.VISITORIP, MAX(S1.DATEENTERED) AS DATEENTERED
FROM STATS S1 
WHERE DATEENTERED BETWEEN '" & OnlineTime & "' AND '" & NOW() & "'
GROUP BY S1.VISITORIP

答案 2 :(得分:1)

您的内部选择在DATEENTERED上使用MAX,但在VisitorIP上不包含groupby。

SELECT S.VISITORIP, S.HTTPADDRESS, S.DATEENTERED
FROM STATS S
JOIN (SELECT S1.VISITORIP, MAX(S1.DATEENTERED)
   FROM STATS S1
   WHERE DATEENTERED BETWEEN '" & OnlineTime & "' AND '" & NOW() & "'
   GROUPBY S1.VISITORIP) S1
ON S.VISITORIP = S1.VISITORIP AND S.DATEENTERED = S1.DATEENTERED
WHERE S.DATEENTERED BETWEEN '" &TIME& "' AND '" & NOW() & "'
GROUP BY S.VISITORIP, S.HTTPADDRESS, S.DATEENTERED
ORDER BY S.DATEENTERED DESC  

答案 3 :(得分:1)

您收到错误是因为您在JOIN中的子选择:

SELECT S1.VISITORIP, MAX(S1.DATEENTERED) FROM STATS S1 WHERE DATEENTERED BETWEEN '" & OnlineTime & "' AND '" & NOW() & "'

尝试聚合“DATEENTERED”,但需要在“VISITORIP”上进行分组才能这样做。

尝试:

SELECT S1.VISITORIP, MAX(S1.DATEENTERED) FROM STATS S1 WHERE DATEENTERED BETWEEN '" & OnlineTime & "' AND '" & NOW() & "' GROUP BY S1.VISITORIP