-4

Let me explain I have an list of employees that say when they actually worked. I have another table that gives me period and begin and Ending Dates for that period. I want a query that will take the day worked and finds the period that it falls in.

table 1

David  05/10/2013
Peter  05/16/2013

table 2
Period_Num         Begin_Period         End_Period
Period 1            01/05/2013        05/15/2013
Period 2            05/16/2013        12/31/2013

I want the final to read:

David      Period 1
Peter      Period 2

Is there a way to do this in sql particularly in a view?

Thanks!

4

3 回答 3

2

Something like

select t1.Name, t2.Period_Num
from table1 as t1
    left outer join table2 as t2 on t1.date between t2.Begin_Period and T2.End_Period

you should be careful, because if periods in table2 are overlapping, your records could duplicate. For example, if your data is:

table 1

David  05/10/2013
Peter  05/16/2013

table 2
Period_Num         Begin_Period         End_Period
Period 1             01/05/2013         05/15/2013
Period 2             05/16/2013         12/31/2013
Period 3             03/08/2013         08/10/2013

you'll receive

David      Period 1
Peter      Period 2
David      Period 3 <- DUPLICATE
于 2013-07-30T15:13:06.943 回答
0

try this

select Table1.Name,Table2.periodNum from Table1 join Table2 on Table1.period between Table2.Begin_Period and Table2.End_Period

于 2013-07-30T15:14:56.167 回答
0

To avoid missing name from table1 in case there is no corresponding period in table2, you can try something like this :

select t1.Name, isnull(t2.Period_Num,'n/a')
from table1 t1
left outer join table2 t2 on t1.worked between t2.Begin_Period and t2.End_Period
于 2013-07-30T15:16:34.717 回答