I have a question about SQL Server.
Table : emp
id | name | sdate | edate
1 | abc | 2003-11-13 | 2003-11-26
1 | def | 2000-04-08 | 2000-04-11
1 | har | 2003-08-01 | 2003-08-31
1 | ka | 2003-10-01 | 2003-10-31
Table: emp1
id | locname | date
1 | a | 2003-10-01
1 | b | 2003-08-01
1 | c | 2000-04-08
1 | d | 2000-04-10
Here emp1 table related date column data fall between emp table sdate and edate.
If we got multiple then we need to consider min(date) related as old record and max(date) records as new records.
If we got single records follow condition then we need to consider same records as old and new record for that date.
If we don't have any records, then we need to consider emp1 table related columns data
Default values and based on this table I want output like below
id | name | sdate | edate | Filter | locname | date
1 | abc | 2003-11-13 |2003-11-26 | new | NA | 1800-01-01(defaultdate)
1 | def | 2000-04-08 |2000-04-11 | new | d | 2000-04-10
1 | har | 2003-08-01 |2003-08-31 | new | b | 2003-08-01
1 | ka | 2003-10-01 |2003-10-31 | new | a | 2003-10-01
1 | abc | 2003-11-13 |2003-11-26 | old | NA | 1800-01-01(defaultdate)
1 | def | 2000-04-08 |2000-04-11 | old | c | 2000-04-08
1 | har | 2003-08-01 |2003-08-31 | old | b | 2003-08-01
1 | ka | 2003-10-01 |2003-10-31 | old | a | 2003-10-01
I tried with this query:
select
max(date) as date, id, name,
sdate, edate, 'New' as Filter, locname
from
(select
a.id, a.name, a.sdate, a.edate, 'New'as Filter,
b.locname, b.date
from
emp a
join
emp1 b on aid = b.id
and CONVERT(VARCHAR(10), CAST(b.date AS DATE), 120) between CONVERT(VARCHAR(10), CAST(ltrim(rtrim(a.sdate)) AS DATE), 120)
and CASE WHEN coalesce(ltrim(rtrim(a.edate)),'') = '' THEN CONVERT(VARCHAR(10), CAST(getdate() AS DATE), 120)
else CONVERT(VARCHAR(10), CAST(ltrim(rtrim(a.edate)) AS DATE), 120) end
) a
group by
date, id, name, sdate, edate, 'New' as Filter, locname
union all
select min(date)as date ,id , name , sdate ,edate,'old'as Filter ,locname from
(select a.id , a.name , a.sdate ,a.edate,'old'as Filter ,b.locname ,b.date from
emp a join emp1 b on aid=b.id
and CONVERT(VARCHAR(10), CAST(b.date AS DATE), 120) between CONVERT(VARCHAR(10), CAST(ltrim(rtrim(a.sdate)) AS DATE), 120)
and CASE WHEN coalesce(ltrim(rtrim(a.edate)),'') = '' THEN CONVERT(VARCHAR(10), CAST(getdate() AS DATE), 120)
else CONVERT(VARCHAR(10), CAST(ltrim(rtrim(a.edate)) AS DATE), 120) end
)a
group by
date ,id , name , sdate ,edate,'New'as Filter ,locname
above query not qiven expected result .please tell me how to write query to achive this task in sql server