我有一个基于id
列的值的SQL Server查询。
就像这样:
SELECT
[id],
COUNT(*) AS IdCount,
FROM
myTable
WHERE
DATEDIFF(day, [Time], GETDATE()) < 30
GROUP BY
[id]
我想把COUNT
结果的值加到WHERE
条件中。我该怎么做?
SELECT
[id],
COUNT(*) AS IdCount,
RANK() OVER (ORDER BY IdCount) CountRank
FROM
myTable
WHERE
DATEDIFF(day, [Time], GETDATE()) < 30
AND {Count values is > 100}
GROUP BY
[id]
2条答案
按热度按时间0lvr5msh1#
SQL不允许在where子句中使用聚合函数,如COUNT或SUM。您可以使用子查询或HAVING函数。您可以查看documentation for a subquery for Microsoft SQL Server。
根据这里提供的信息,我怀疑HAVING子句可能会更容易地解决您的问题。请参阅documentation for the HAVING clause。
fykwrbwg2#
聚合函数不能在where子句中使用,但可以在group by下面的having子句中添加它们: