缩短SQL服务器选择计数查询

时间:2016-02-11 14:01:45

标签: sql-server count

我对SQL比较新,我正在尝试创建一个选择计数查询。它基本上是在不同条件下多次重复表达。有没有办法让代码更有效率,因为我有20多个不同的'条件组'。以下是显示2个条件组的示例。

(select count(vps.PrimaryKey) 
   from V_PatentSummarized vps 
            inner join V_TechnologySummarized vts 
                  on vts.PrimaryKey=vps.TechnolFK 
  where (vts.ClientDepartments like '%22%' or vts.ClientDepartments like '%12%') 
    and vps.FileDate between '2015-11-01 00:00:00.000' 
                         and '2016-01-31 00:00:00.000') as Sciences

(select count(vps.PrimaryKey) 
   from V_PatentSummarized vps 
          inner join V_TechnologySummarized vts 
                on vts.PrimaryKey=vps.TechnolFK 
  where (vts.ClientDepartments like '%36%' or vts.ClientDepartments like '%42%') 
    and vps.FileDate between '2015-11-01 00:00:00.000' 
                         and '2016-01-31 00:00:00.000') as Arts

2 个答案:

答案 0 :(得分:4)

只要所有这些子查询使用相同的FROM子句,您就可以使用CASE语句缩短它:

SELECT 
 SUM(CASE WHEN (vts.ClientDepartments like '%22%' or vts.ClientDepartments like '%12%') 
    and vps.FileDate between '2015-11-01 00:00:00.000' 
                         and '2016-01-31 00:00:00.000'
      THEN 1 ELSE 0 END) AS Sciences
 SUM(CASE WHEN (vts.ClientDepartments like '%36%' or vts.ClientDepartments like '%42%') 
    and vps.FileDate between '2015-11-01 00:00:00.000' 
                         and '2016-01-31 00:00:00.000'
      THEN 1 ELSE 0 END) AS Arts
   from V_PatentSummarized vps 
          inner join V_TechnologySummarized vts 
                on vts.PrimaryKey=vps.TechnolFK 

此外,如果所有子查询具有相同的FileDate范围,则可以将该过滤器向下移动到主WHERE子句,而不是将其放在每个CASE表达式中。

答案 1 :(得分:1)

尝试查看视图,您还需要在视图中区分相同的列

create view vwname
as
select * 
   from V_PatentSummarized vps 
            inner join V_TechnologySummarized vts 
                  on vts.PrimaryKey=vps.TechnolFK 
  where 
     vps.FileDate between '2015-11-01 00:00:00.000' 
                         and '2016-01-31 00:00:00.000'

-----现在您可以查询

   select count(primarykey) from vwname where clauses