我正在使用ROW_NUMBER()和派生表从派生表结果中获取数据。
但是,我收到错误消息,告诉我在GROUP BY子句中没有相应的列。
这是错误:
列'tblCompetition.objID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中
我错过了什么专栏?或者我做错了什么?在下面查找不起作用的查询,以及正在运行的(更简单)查询。
SQL Server 2008。
查询不起作用:
SELECT
objID,
objTypeID,
userID,
datAdded,
count,
sno
FROM
(
SELECT scc.objID,scc.objTypeID,scc.userID,scc.datAdded,
COUNT(sci.favID) as count,
ROW_NUMBER() OVER(PARTITION BY scc.userID ORDER BY scc.unqID DESC) as sno
FROM tblCompetition scc
LEFT JOIN tblFavourites sci
ON sci.favID = scc.objID
AND sci.datTimeStamp BETWEEN @datStart AND @datEnd
) as t
WHERE sno <= 2 AND objTypeID = @objTypeID
AND datAdded BETWEEN @datStart AND @datEnd
GROUP BY objID,objTypeID,userID,datAdded,count,sno
正在运行的简单查询:
SELECT objId,objTypeID,userId,datAdded FROM
(
SELECT objId,objTypeID,userId,datAdded,
ROW_NUMBER() OVER(PARTITION BY userId ORDER BY unqid DESC) as sno
FROM tblResdagbokenCompetition
) as t
WHERE sno<=2 AND objtypeid=@objTypeID
AND datAdded BETWEEN @datStart AND @datEnd
谢谢!
答案 0 :(得分:2)
你不能在group by子句中计算。实际上,当您在group by中有其他字段时,会计算计数。从您的分组中删除计数。
答案 1 :(得分:2)
在您使用的最里面的查询中
COUNT(sci.favID) as count,
这是一个聚合,您可以选择其他非聚合列。
我相信你想要一个分析COUNT
代替:
SELECT objID,
objTypeID,
userID,
datAdded,
count,
sno
FROM (
SELECT scc.objID,scc.objTypeID,scc.userID,scc.datAdded,
COUNT(sci.favID) OVER (PARTITION BY scc.userID ) AS count,
ROW_NUMBER() OVER (PARTITION BY scc.userID ORDER BY scc.unqID DESC) as sno
FROM tblCompetition scc
LEFT JOIN
tblFavourites sci
ON sci.favID = scc.objID
AND sci.datTimeStamp BETWEEN @datStart AND @datEnd
) as t
WHERE sno = 1
AND objTypeID = @objTypeID
答案 2 :(得分:2)
你的子查询中需要GROUP BY,因为聚合的位置是:
SELECT
objID,
objTypeID,
userID,
datAdded,
count,
sno
FROM
(
SELECT scc.objID,scc.objTypeID,scc.userID,scc.datAdded,
COUNT(sci.favID) as count,
ROW_NUMBER() OVER(PARTITION BY scc.userID ORDER BY scc.unqID DESC) as sno
FROM tblCompetition scc
LEFT JOIN tblFavourites sci
ON sci.favID = scc.objID
AND sci.datTimeStamp BETWEEN @datStart AND @datEnd
GROUP BY scc.objID,scc.objTypeID,scc.userID,scc.datAdded) as t
WHERE sno <= 2 AND objTypeID = @objTypeID
AND datAdded BETWEEN @datStart AND @datEnd