我有一张包含所有代理记录的表格。我设置了几个查询,计算这些记录的具体内容,每个查询按日期对它们进行分组。我想弄清楚的是我如何将这些查询组合成一个新的查询。现在,我运行每个,将它们放入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
有什么建议吗?谢谢!
答案 0 :(得分:0)
您可以使用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