| Author |
Topic |
|
akpaga
Constraint Violating Yak Guru
331 Posts |
Posted - 2011-08-12 : 16:57:24
|
| i have a table customercustomer_no, begintime,end time1,0,02,0,03,8,94,0,05,7,8,6,0,07,9,11Second table agentsagent_ID,starttimeX,10y,12z,7,k,10What i want to basically do is outer join the tow tables for a reasonWhen I do i want to leave out the records in Customer table that are not zero for agents whose start time do not lie between the begintime and endtime of customer but if the starttime of the agent is between the begintime and endtime of customer then it shud be considered for join.The 0 begin time and end time are shud be always considered.resultset example i wnat to see after joining 1,0,0 ,X,102,0,0,X,10 4,0,0,X,10 6,0,0,X,107,9,11,X,10and so on for other agents as well....Hope i am clear |
|
|
Nikhil1home
Starting Member
23 Posts |
Posted - 2011-08-12 : 19:20:20
|
| Sorry to be blunt here but this seems like a poor database design to me.You don't need an our join here. You need two queries and combine their results with a union. What is the purpose of the query? It seems wierd.First query will cross join all agents with customers who have 0s in begin and end fields. The second query will perform an inner join between agents and the customers who have non-zero value in begin or end field. You need to combine these two queries with a union.SELECT customer_no, begintime,endtime, agent_ID,starttimeFROM customer CROSS JOIN agentsWHERE customer.begintime = 0 AND customer.endtime = 0UNIONSELECT customer_no, begintime,endtime, agent_ID,starttimeFROM customer JOIN agents ON agents.starttime BETWEEN customer.begintime AND customer.endtime WHERE customer.endtime > 0 |
 |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-08-13 : 13:35:28
|
| /*customer_no, begintime,end time1,0,02,0,03,8,94,0,05,7,8,6,0,07,9,11Second table agentsagent_ID,starttimeX,10y,12z,7,k,101,0,0 ,X,102,0,0,X,104,0,0,X,106,0,0,X,107,9,11,X,10*/DECLARE @Table1 TABLE (CustNo int,begintime int,endtime int)DECLARE @Table2 TABLE (agent char(1),startTime int)INSERT INTO @Table1SELECT 1,0,0 UNION ALLSELECT 2,0,0 UNION ALLSELECT 3,8,9 UNION ALLSELECT 4,0,0 UNION ALLSELECT 5,7,8 UNION ALLSELECT 6,0,0 UNION ALLSELECT 7,9,11INSERT INTO @Table2SELECT 'X',10 UNION ALLSELECT 'y',12 UNION ALLSELECT 'z',7 UNION ALLSELECT 'k',10SELECT t1.CustNo,t1.BeginTime,t1.EndTime,t2.Agent,t2.StartTimeFROM @table1 t1 CROSS JOIN @table2 t2WHERE (t1.BeginTime = 0 and t1.EndTime = 0)OR (t2.StartTime between t1.BeginTime and t1.EndTime) JimEveryday I learn something that somebody else already knew |
 |
|
|
|
|
|