首页 > 解决方案 > 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

enter image description here

I like to know how many times the did is repeating in the result

标签: sql-server

解决方案


我想这是因为您没有为子查询设置别名。您还缺少外部查询中的分组。您的查询格式也可以改进:

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 是文档的主键,因此在这种情况下不会出现重复项)


推荐阅读