sql-server 如何在Where子句中使用Count结果

h9vpoimq  于 2022-10-31  发布在  其他
关注(0)|答案(2)|浏览(352)

我有一个基于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]
0lvr5msh

0lvr5msh1#

SQL不允许在where子句中使用聚合函数,如COUNT或SUM。您可以使用子查询或HAVING函数。您可以查看documentation for a subquery for Microsoft SQL Server
根据这里提供的信息,我怀疑HAVING子句可能会更容易地解决您的问题。请参阅documentation for the HAVING clause

SELECT 
    [id], 
    COUNT(*) AS IdCount,   
FROM  myTable  
WHERE DATEDIFF(day,[Time],GETDATE()) < 30
GROUP BY [id]
HAVING COUNT(IdCount) > SOMENUMBER
fykwrbwg

fykwrbwg2#

聚合函数不能在where子句中使用,但可以在group by下面的having子句中添加它们:

select id
from table
group by id
having count(*)>1

相关问题