似乎您希望提供处于给定状态和日期范围内的任何公司的列表。当我们意识到您希望了解在提供的日期范围内具有任何状态的任何公司时,这似乎就不那么复杂了。
一家公司的状态为1,并在日期范围内更改为不同的状态(是)
一家公司处于状态1,在日期范围后更改为不同的状态(是)
--TEST DATA
create table #company
(
id int identity not null,
name varchar(222) not null,
status int not null,
status_effective_date datetime not null
)
create table #companystatus
(
id int identity not null,
company_id int not null,
status int not null,
status_effective_date datetime not null
)
insert into #company (name,status,status_effective_date) values('foo',1,'12/31/2017')
insert into #company (name,status,status_effective_date) values('biz',2,'11/30/2017')
insert into #company (name,status,status_effective_date) values('baz',1,'12/31/2017')
insert into #company (name,status,status_effective_date) values('bloh',3,'11/30/2017')
insert into #company (name,status,status_effective_date) values('blee',4,'12/31/2017')
declare @fooid int
set @fooid = (select id from #company where name = 'foo')
declare @bizid int
set @bizid = (select id from #company where name = 'biz')
declare @bazid int
set @bazid = (select id from #company where name = 'baz')
declare @blohid int
set @blohid = (select id from #company where name = 'bloh')
insert into #companystatus (company_id,status,status_effective_date) values (@fooid,2,'1/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@bizid,5,'3/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@bazid,4,'2/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@blohid,1,'2/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@fooid,2,'4/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@fooid,4,'9/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@bizid,2,'5/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@bazid,1,'10/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@blohid,3,'7/1/2018')
insert into #companystatus (company_id,status,status_effective_date) values (@fooid,1,'6/1/2018')
--get only one distinct company id and name where the status date is between my two dates and the status is the value I have chosen (1)
select distinct(cn.id), cn.name from #companystatus c
join #company cn on
cn.id = c.company_id
where c.status_effective_date between '1/1/2017' and '5/1/2018'
and c.status in (1)
--replace the dates and status with what you want
--clean up
drop table #company
drop table #companystatus