你的问题并不清楚,无论如何,如果我正确地理解你的问题,下面是解决方案
declare @element_name varchar(1)= 'a'
declare @element_value int = 25
declare @element_effective_date smalldatetime ='7/15/2016'
--'7/25/2016'
--'8/5/2016'
create table #a(
id int,
person_id int,
element_name varchar(1),
element_value int,
element_effective_date smalldatetime)
insert into #a
select 1, 123, 'a', 25,'07/01/2016' union
select 2, 123, 'b', 100,'05/01/2016' union
select 3, 123, 'a', 25,'07/20/2016' union
select 4, 456, 'b', 101,'01/01/2016' union
select 5, 456, 'b', 102,'04/01/2016' union
select 6, 456, 'a', 25,'08/01/2016' union
select 7, 789, 'b', 101,'08/01/2016' union
select 8, 789, 'c', 200,'07/25/2016' union
select 9, 789, 'd', 201,'07/26/2016'
select *
Into #solutionDataset
from #a
where [email protected]_name
and [email protected]_value
and element_effective_date < @element_effective_date
/*
I want to select the person_ids from the table for a selected element_name where the element_value is equal to some value and the rows' effective date is equal to a given date or is the first row for the person_id with the effective date less than the given date.
*/
if(@@ROWCOUNT=1)
begin
select * from #solutionDataset
end
else
begin
select * from #solutionDataset
where id not in(select min(id) from #a where [email protected]_name and [email protected]_value)
end
如果你存储在您的入住日期您的生活会更容易在ISO格式,而不是(疯狂)美国格式。如果日期列的数据类型是“日期”而不是“文本”,那么你的生活会更容易*。我建议首先解决其中的一个问题,然后你就不必问这个问题。 – Bohemian
标记使用的dbms。 (许多产品都有自己的非ANSI功能,用于日期/时间。) – jarlh
还可添加预期结果。 – jarlh