将多个查询合并为 1 个新查询

Combining several queries into 1 new query

我有一个 table,其中包含我们所有的代理记录。我设置了几个查询来计算这些记录的特定内容,并且每个查询都按日期对它们进行分组。我想弄清楚的是如何将这些查询组合成一个新查询。现在,我 运行 每个,将它们放入 Excel 然后进行 vlookup 并将它们组合成一个。这只是我的两个查询。

查询 #1:

select 
    LocationStateAbr,
    count(LocationStateAbr) as "Total Agencies" 
from
    [PROD_Agency].[dbo].[AgAgency]
where 
    StatusId = ' ' 
    and BusinessId in ('b', 'C') 
    and TypeId in ('A', 'C', 'F', 'I', 'X') 
group by 
    LocationStateAbr
order by 
    LocationStateAbr ASC

查询#2:

select 
    LocationStateAbr,
    count(LocationStateAbr) as "New Agencies" 
from
    [PROD_Agency].[dbo].[AgAgency]
where 
    year(AppointedDt) = 2018 
    and StatusId = ' ' 
    and BusinessId in ('b', 'C') 
    and TypeId in ('A', 'C', 'F', 'I', 'X') 
group by 
    LocationStateAbr
order by 
    LocationStateAbr ASC

有什么建议吗?谢谢!

您可以使用 CASE 将两个查询合二为一。在您的情况下,它将是这样的:

select 
    LocationStateAbr,
    count(case when StatusId = ' ' 
          and BusinessId in ('b', 'C') 
          and TypeId in ('A', 'C', 'F', 'I', 'X') then 1 else null end) as "Total Agencies",
    count(case when year(AppointedDt) = 2018 
          and StatusId = ' ' 
          and BusinessId in ('b', 'C') 
          and TypeId in ('A', 'C', 'F', 'I', 'X') the 1 else null end) as "New Agencies"
FROM
   [PROD_Agency].[dbo].[AgAgency]
group by 
    LocationStateAbr
order by 
    LocationStateAbr ASC