Hi Everyone,
I need some help writing a query that joins a table to a UNION query. I was wondering what is the most efficent way to do this.
Tables
Employees (EMPID, FULLNAME)
DailySchedules (SCHID,EMPID, SCHDATE,DEPTID)
GeneralSegments (GSID,EMPID,STARTTIME,STOPTIME)
DetailSegments (DSID,EMPID,STARTTIME,STOPTIME)
I need to join the records from GeneralSegments and DetailSegments THEN inner join DailySchedules and Employees.
Query must output:
EMPID, FULLNAME, SCHDATE,STARTTIME,STOPDTIME
Thank You
Can you provide some sample data (preferrably in the form of insert statements) along with a data representation of what you want for output?
Thanks.
|||Untested, but, it should give you an idea
Code Snippet
SELECT Segments.EMPID,
Employees.FULLNAME,
DailySchedules.SCHDATE,
Segments.STARTTIME,
Segments.STOPDTIME
FROM
(
SELECT EMPID, STARTTIME, STOPTIME FROM GeneralSegments
UNION
SELECT EMPID, STARTTIME, STOPTIME FROM DetailSegments
) Segments
INNER JOIN Employees
ON Employees.EMPID = Segments.EMPID
INNER JOIN DailySchedules
ON DailySchedules.EMPID = Segments.EMPID
Hi David,
That example will work. One question though, I have to display the next 14 days (2 weeks) on the web. Where should I place my WHERE clause? In the outer query or include the date range in both union statements?
ie. WHERE SCHDATE BETWEEN GETDATE() AND GETDATE() + 14
Thank You
|||Is SCHDATE column present in the tables in the DailySchedule table or the segments tables? In any case, it doesn't matter. SQL Server will automatically roll the schdate predicate into the inner queries as well based on their reference. For example, if you want to filter on STARTTIME then you can include just one WHERE clause like below and it will be applied to both GeneralSegments & DetailSegments
Code Snippet
SELECT Segments.EMPID,
Employees.FULLNAME,
d.SCHDATE,
Segments.STARTTIME,
Segments.STOPDTIME
FROM
(
SELECT EMPID, STARTTIME, STOPTIME FROM GeneralSegments
UNION
SELECT EMPID, STARTTIME, STOPTIME FROM DetailSegments
) Segments
INNER JOIN Employees
ON Employees.EMPID = Segments.EMPID
INNER JOIN DailySchedules
ON DailySchedules.EMPID = Segments.EMPID
WHERE Segments.STARTTIME >= @.Start
No comments:
Post a Comment