我有一个类似于此
的数据结构UserID| Rating | CreatedDate |
------+--------+-------------+
101 | 10 | 21-02-2018 |
101 | 10 | 18-02-2018 |
102 | 6 | 12-01-2018 |
103 | 3 | 01-02-2018 |
101 | 8 | 25-03-2018 |
102 | 2 | 21-02-2017 |
101 | 1 | 21-08-2017 |
我试图从SQL Server 2017中检索特定用户给出的所有不同评级(1-10)的计数。
我正在使用此代码:
SELECT Rating, COUNT(Rating) AS Count
FROM dbo.tableName
GROUP BY Rating, UserId
HAVING (COUNT(Rating) >= 1) AND (UserId = '101')
ORDER BY Count DESC
我遇到的问题是,我希望仅针对过去5周内创建的条目运行此查询,以过滤我之前使用的过去5周:
(CreatedDateTime > DATEADD(week, - 5, GETDATE())) AND (Recommend IS NOT NULL)
但与Count
混合时,此功能不再有效。我在
CreatedDateTime在having子句中无效,因为它不包含在聚合函数或group by子句中
有人可以帮助我获得正确的语法吗?
答案 0 :(得分:3)
我认为您的标准应该在WHERE
条款中:
SELECT
Rating,
COUNT(Rating) AS Count
FROM dbo.tableName
WHERE
CreatedDateTime > DATEADD(week, - 5, GETDATE()) AND
Recommend IS NOT NULL
GROUP BY
Rating,
UserId
HAVING
COUNT(Rating) >= 1 AND UserId = '101'
ORDER BY
Count DESC
这应该限制仅在过去五周内发生的记录,以及Recommend
不为NULL的记录。
您收到错误的原因是,在评估HAVING
子句时,数据库正在处理记录聚合。由于CreatedDateTime
字段不是聚合,因此导致错误。
答案 1 :(得分:3)
将您的行过滤器移至WHERE
,并在HAVING
上保留汇总过滤器。
SELECT
Rating,
COUNT(Rating) AS Count
FROM
dbo.tableName
WHERE
UserId = '101' AND
CreatedDateTime > DATEADD(week, - 5, GETDATE()) AND
Recommend IS NOT NULL
GROUP BY
Rating
HAVING
COUNT(Rating) >= 1
ORDER BY
Count DESC
SQL引擎过滤器使用WHERE
条件过滤数据,然后使用GROUP BY
列对行进行分组,最后应用HAVING
条件来过滤分组结果。