我有一个按ID分组的表,想按日期过滤
StudentTable
DateTime StudentId Grade
SELECT DateTime, StudentId, AVG(Grade)
FROM StudentTable
WHERE CONVERT(DATE, DateTime, 102) BETWEEN CONVERT(DATE, '11-1-2018', 102)
AND CONVERT(DATE, '12-02-2018', 102)
GROUP BY StudentId
但这给我错误 选择列表中的“ DateTime”列无效,因为它不包含在聚合函数或GROUP BY子句中。我该怎么办?谢谢进阶
答案 0 :(得分:0)
这解决了我的问题。但是,如果您有更好的解决方案,请告诉我。
SELECT StudentId, AVG (Grade) FROM
(SELECT * FROM StudentTable
WHERE CONVERT(DATE, DateTime, 102) BETWEEN CONVERT(DATE, '11-1-2018', 102)
AND CONVERT(DATE, '12-02-2018', 102)
) MainT
GROUP BY MainT.StudentId
答案 1 :(得分:-1)
只需使用 BETWEEN 子句,而不是将String Date手动转换为Date。
SELECT DateTime, StudentId, AVG(Grade)
FROM StudentTable
WHERE DateTime BETWEEN '11-1-2018' AND '12-02-2018'
GROUP BY StudentId;
从W3Schools检索。