sql-server - sql count query over a count query
问题描述
following is my query to get the count of documentid
select count(did),did
from (
select count(FileDataId) as fid,
documentid as did,
FileDataId
from DocumentHistory
where documentid in (
select documentid
from Document
where DocumentTypeId=11 and
IsVerified=0 and
lastmodified < '5/jan/2019'
)
group by DocumentId,
filedataid
having count(FileDataId)<2
)
I am getting error as
Incorrect syntax near ')'.
If i run the inner query, it is bringing me result
I like to know how many times the did is repeating in the result
解决方案
我想这是因为您没有为子查询设置别名。您还缺少外部查询中的分组。您的查询格式也可以改进:
select
count(a.did),
a.did
from (
select
count(dh.FileDataId) as fid,
dh.documentid as did,
dh.FileDataId
from DocumentHistory dh
INNER JOIN Document d on d.documentid = dh.documentid
where d.DocumentTypeId=11 and d.IsVerified=0 and d.lastmodified < '2019-01-05'
group by DocumentId, filedataid
having count(FileDataId)<2
) a
GROUP BY did
除了结合 simon 关于日期格式的建议(yyyy-mm-dd 是 ISO,并且不受本地化问题的影响,例如包含单词的日期 - 您的查询可能不适用于例如西班牙数据库),我将 IN 换成了INNER JOIN 也是;尽管查询优化器通常可以重写 IN 以使其表现得像一个连接,但您应该避免将 IN 用于比您准备手动编写的列表更长的列表。一些数据库对连接的优化比在
请注意,话虽如此,INNER JOIN 和 IN 之间的行为略有不同,如果 IN(...) 列表包含重复项,您将不会从 documenthistory 结果中获得重复的行,但您会使用内部连接。(我希望 documentid 是文档的主键,因此在这种情况下不会出现重复项)
推荐阅读
- typescript - 相似类型约束和条件类型的区别
- microservices - Ocelot Cache - 如何通过网关仅缓存来自微服务的成功(200)响应
- python - 获取最新构建 jenkin 作业的控制台输出并将其传递给 python
- c++ - 我正在尝试对某些用户定义的数据类型的向量进行排序,但它给了我语法错误 c++
- .net - 如何使用 EntityFrameworkCore 5 执行包中的 oracle 11g SP
- flutter - 燃烧火柴的颤动动画
- ios - 在 CI 上的 UI 测试不稳定
- rust - actix web - sqlx - juniper:我得到'尝试使用同步解析器解析 Some("Query") 类型的异步字段用户'
- jquery - 如何在 laravel 中使用 ajax 上传文件?
- java - Android studio 如何从 CalendarView 获取 int 值(年、月、日)并使用它保存在 SQLite 中