How to retrieve all grand parents at once - sql

I have two simple tables in SQLITE3 (family bonds):
"persons" (id, fname, lname)
"relationships" (parent/child)
I would like to get each grand children along with all their grand parents (from 1 to 4 of them depending on the grand child) so that 1 row result =
Distinct Grand child, Grand parent 1, Grand parent 2, Grand parent 3, Grand parent 4
Thanks to Caius Jard, I've been able to get each child and its grand parents in another star overflow question. However, so far I have:
1 line = Grand child, 1 grand parent (so it needs up to 4 lines to get all grand parents of a child).
SELECT c.fname, c.lname, gp.fname, gp.lname
FROM relations p_c
INNER JOIN relationships gp_p ON gp_p.child = p_c.parent
INNER JOIN persons gp ON gp.id = gp_p.parent
INNER JOIN persons c ON c.id = p_c.child
ORDER BY c.id;
How could I edit this so that I get each grand child along with all the grand parents in one single row result?
If possible only using SELECT (+ count/distinct), WHERE (+in/exists), INNER/LEFT JOIN, GROUP BY (+having), ORDER BY.

We can turn rows into columns by a technique known as conditional aggregation:
Suppose you have a result set:
x, y
1, hello
2, goodbye
If you wrote this:
SELECT x,
CASE WHEN x = 1 THEN y END as x1,
CASE WHEN x = 2 THEN y END as x2
FROM ...
You would get this:
x, x1, x2
1, hello, NULL
2, NULL, goodbye
There is only one value in a column, the rest are null. If you then use e.g. MAX, which discards nulls:
SELECT
MAX(CASE WHEN x = 1 THEN y END) as x1,
MAX(CASE WHEN x = 2 THEN y END) as x2
FROM ...
You would get
x1, x2
hello, goodbye
We've had to drop the x, because we can't put it in there otherwise we'd have to group it, which would prevent rows collapsing down
Now to your query, we probably have to add other info in because we need something to CASE WHEN on. You don't indicate that we can arbitrarily throw a row number in there. Hopefully persons contains a gender indicator because 4 grandparents are the result of two males and two females arising from one male and one female (so we have MM - father's father, MF - father's mother, FM and FF etc)
SELECT ...
FROM relations p_c
INNER JOIN relationships gp_p ON gp_p.child = p_c.parent
INNER JOIN persons gp ON gp.id = gp_p.parent
INNER JOIN persons p ON p.id = p_c.parent
INNER JOIN persons c ON c.id = p_c.child
We can now query the gender of each level of family tree:
SELECT c.name as child,
CASE WHEN gp.gender = 'm' AND p.gender = 'm' THEN gp.name END AS fathersfather,
CASE WHEN gp.gender = 'm' AND p.gender = 'f' THEN gp.name END AS fathersmother,
CASE WHEN gp.gender = 'f' AND p.gender = 'm' THEN gp.name END AS mothersfather,
CASE WHEN gp.gender = 'f' AND p.gender = 'f' THEN gp.name END AS mothersmother
FROM relations p_c
INNER JOIN relationships gp_p ON gp_p.child = p_c.parent
INNER JOIN persons gp ON gp.id = gp_p.parent
INNER JOIN persons p ON p.id = p_c.parent
INNER JOIN persons c ON c.id = p_c.child
This will give the child and then a diagonal array of the grandparent names. You can squish it to a row per child with:
SELECT c.name as child,
MAX(CASE WHEN gp.gender = 'm' AND p.gender = 'm' THEN gp.name END) AS fathersfather,
MAX(CASE WHEN gp.gender = 'm' AND p.gender = 'f' THEN gp.name END) AS fathersmother,
MAX(CASE WHEN gp.gender = 'f' AND p.gender = 'm' THEN gp.name END) AS mothersfather,
MAX(CASE WHEN gp.gender = 'f' AND p.gender = 'f' THEN gp.name END) AS mothersmother
FROM relations p_c
INNER JOIN relationships gp_p ON gp_p.child = p_c.parent
INNER JOIN persons gp ON gp.id = gp_p.parent
INNER JOIN persons p ON p.id = p_c.parent
INNER JOIN persons c ON c.id = p_c.child
GROUP BY c.name

Instead of 4 columns for the grand parents, I would suggest to use GROUP_CONCAT() and get 1 column with all the grandparents:
SELECT p.fname, p.lname,
GROUP_CONCAT(gp.fname || ' ' || gp.lname, '|')
FROM persons p
INNER JOIN relationships r1 ON r1.child = p.id
INNER JOIN relationships r2 ON r2.child = r1.parent
INNER JOIN persons gp ON r2.parent = gp.id
GROUP BY p.id
The code is by far simpler.
Use LEFT joins instead of INNER joins if you want all the persons returned, even the ones without grandparents.

Assuming there are four grandparents, you can enumerate them and aggregate:
SELECT fname, lname,
MAX(CASE WHEN seqnum = 1 THEN grandparent_name END) as grandparent_1,
MAX(CASE WHEN seqnum = 2 THEN grandparent_name END) as grandparent_2,
MAX(CASE WHEN seqnum = 3 THEN grandparent_name END) as grandparent_3,
MAX(CASE WHEN seqnum = 4 THEN grandparent_name END) as grandparent_4
FROM (SELECT c.id, c.fname, c.lname,
gp.fname || ' ' || gp.lname as grandparent_name,
ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY gp.fname, gp.lanme) as seqnum
FROM relations p_c JOIN
relationships gp_p
ON gp_p.child = p_c.parent JOIN
persons gp
ON gp.id = gp_p.parent
persons c
ON c.id = p_c.child
) cgp
GROUP BY fname, lname, id;

Related

SQL query where has children with conditions

Let's say I have:
a parents table with the following columns: (id, name)
a children attributes table with the following columns: (id, child_id, parent_id, attribute, attribute_value)
Now I want to filter any parent id's that has at least a child with both:
attribute => intelligence of 5
attribute => health of 4
Either one child with intelligence of 5 and health of 4, or one child has intelligence of 5 and another child has health of 4.
How would you query that, in PostgreSQL? Thank you
You can just do the intersection of
parents that have children with intelligence 5
parents that have children with health 4
(SELECT parent_id
FROM tab
WHERE attribute = 'intelligence'
AND attribute_value = 5 )
INTERSECT
(SELECT parent_id
FROM tab
WHERE attribute = 'health'
AND attribute_value = 4 )
If you only wants parents info:
SELECT
DISTINCT parents.id, parents.name
FROM
parents
LEFT JOIN attributes ON parents.id = attributes.parent_id
WHERE
(attribute = 'intelligence' AND attribute_value = 5)
OR (attribute = 'health' AND attribute_value = 4)
First we need to join the tables -- like this
select p.id as p_id, p.name as parent_name,
k.* -- we won't need this in later versions
from parent p
join kidatt k on p.id = k.parent_id
now we have two attributes we care about -- let make a query that shows those
select p.id as p_id, p.name as parent_name,
case when k.attribute = 'intelligence' and k.attribute_value = 5 then 1 else 0 end as has_a1,
case when k.attribute = 'health' and k.attribute_value = 4 then 1 else 0 end as has_a2
from parent p
join kidatt k on p.id = k.parent_id
we now have a query with a 1 in a row for those that have each of these
now we group by the parent.
select p.id as p_id, p.name as parent_name,
SUM(case when k.attribute = 'intelligence' and k.attribute_value = 5 then 1 else 0 end) as has_a1,
SUM(case when k.attribute = 'health' and k.attribute_value = 4 then 1 else 0 end) as has_a2
from parent p
join kidatt k on p.id = k.parent_id
group by p.id, p.name
now we have a query where a1 and a2 are greater than 0 if one or more child has it.
Now just select the results
select *
from (
select p.id as p_id, p.name as parent_name,
SUM(case when k.attribute = 'intelligence' and k.attribute_value = 5 then 1 else 0 end) as has_a1,
SUM(case when k.attribute = 'health' and k.attribute_value = 4 then 1 else 0 end) as has_a2
from parent p
join kidatt k on p.id = k.parent_id
group by p.id, p.name
)
where has_a1 > 0 and has_a2 > 0
note -- I did not write this query to be the best way to solve this problem -- instead I wrote it in a way to show you how to "think" in SQL and solve the problem with a series of steps.
I'd have to test to be sure, but I expect this would be the fastest way to do this query (depends on data and indexes etc.)
select distinct p.id as p_id, p.name as parent_name,
from parent p
join kidatt k on p.id = k.parent_id
where k.attribute = 'intelligence' and k.attribute_value = 5
intersect
select distinct p.id as p_id, p.name as parent_name,
from parent p
join kidatt k on p.id = k.parent_id
where k.attribute = 'health' and k.attribute_value = 4

SQL Counting Using Group By With Multiple Tables and Joins

I have 3 tables (Schools, Students, Activities) such as simply like these:
School
Student
Activity
I want to get the list for each school the ALL activities and number of participants according to the gender in the 2020 ONLY like this table:
I did a query like this but it didn't worked as I wanted:
SELECT Sc.SchoolName, A.ActivityName, Sc.Year COUNT(Gender)
FROM School Sc
JOIN Student S ON Sc.SchoolID=S.SchoolID
JOIN Activity A ON S.ActivityID=A.ActivityID
GROUP BY Gender
How can I fix this? Can you give me solution?
You want conditional aggregation:
SELECT
Sc.SchoolName,
A.ActivityName,
Sc.Year,
SUM(CASE WHEN S.Gender = 'F' THEN 1 ELSE 0 ENd) F,
SUM(CASE WHEN S.Gender = 'M' THEN 1 ELSE 0 ENd) M
FROM School Sc
JOIN Student S ON Sc.SchoolID = S.SchoolID
JOIN Activity A ON S.ActivityID = A.ActivityID
GROUP BY
Sc.SchoolName,
A.ActivityName,
Sc.Year
SELECT
Sc.SchoolName,
A.ActivityName,
Sc.Year,
COUNT(CASE WHEN S.Gender = 'F' THEN StudentID END) as F,
COUNT(CASE WHEN S.Gender = 'M' THEN StudentID END) as M
FROM School Sc
INNER JOIN Student S ON Sc.SchoolID = S.SchoolID
INNER JOIN Activity A ON S.ActivityID = A.ActivityID
WHERE YEAR LIKE '2020-%'
GROUP BY
Sc.SchoolName,
A.ActivityName,
Sc.Year
Please use below query,
SELECT Sc.SchoolName, Sc.Year, A.ActivityName,
case when Sc.Gender = 'M' then count(1) end as M,
case when Sc.Gender = 'F' then count(1) end as F
FROM School Sc
JOIN Student S ON Sc.SchoolID=S.SchoolID
JOIN Activity A ON S.ActivityID=A.ActivityID
GROUP BY Sc.SchoolName, Sc.Year, A.ActivityName;

SQL : Percentage Completed

I need to have a SQL query to calculate the percentage of courses completed by location which are different SQL tables.
Courses table has a Status = 'C' (Completed status).
select Locations.Name, ( ??? ) as PercentCompleted
from Locations inner join Candidates ON Locations.Id = Candidates.SpecifiedLocation
inner join Courses on Candidates.Id = Courses.CandidateId
Group By Locations.Name
I want the results to be:
Location PercentCompleted
Loc1 10
Loc2 50
Loc3 75
where 10, 50 and 75 are percentages of courses completed per location.
Can this be achieved with a single SQL query?
If I understand correctly, I think you can do:
select l.Name,
avg(case when co.status = 'C' then 100.0 else 0 end) as PercentCompleted
from Locations l inner join
Candidates c
on l.Id = c.SpecifiedLocation inner join
Courses co
on c.Id = co.CandidateId
group by l.name;
try like below
select Locations.Name, (sum(case when Status = 'C' then 1 else 0 end)/(select count(*)
from Candidates c where c.SpecifiedLocation=Locations.Id))*100
as PercentCompleted
from Locations inner join Candidates ON Locations.Id = Candidates.SpecifiedLocation
inner join Courses on Candidates.Id = Courses.CandidateId
Group By Locations.Name

Using some column data for values and some for ID

Slowly but surely I'm getting the hang of this. I created a report using the following query, which works perfectly. I'll give an example of the result below the query.
Select p.parent_program_id, p.program_id, p.name, p.copyright, p.active_flag,
max(Case when c.category_id = 36261 Then 'X' Else ' ' End) As CC_Indicator,
max(Case when c1.category_id = 36362 Then 'X' Else ' ' End) As CC_Badge,
max(Case when c2.category_id = 43221 Then 'X' Else ' ' End) As CC_Solution
From tbl_program p
Join xref_category_program xcp
On p.program_id=xcp.program_id
left Join tbl_category c
On xcp.category_id=c.category_id and c.category_id = 36261
left Join tbl_category c1
On xcp.category_id=c1.category_id and c1.category_id = 36362
left Join tbl_category c2
On xcp.category_id=c2.category_id and c2.category_id = 43221
where xcp.category_id in(36261,36362,43221)
group by p.program_id, p.name, p.copyright, p.active_flag, p.parent_program_id
Order by p.program_id
The results look like this (leaving out some unimportant columns for brevity's sake):
P.ParentProgramID P.ProgramID CC_Indicator CC_Badge CC_Solution
00001 12111 X
null 20200 X X X
null 00001 X X
The Indicator/Badge/Solution is identified by a category id. Now the people requesting this report want it sorted by company, which are also assigned category ids in the same column.
Assuming something like xcp.category_id values for company were 11111/22222/33333/44444, how would I put that in another column in this report in an order decided by the receivers of the report?
Something that looked like this, assuming a total of 6 records...
P.ParentProgramID P.ProgramID CC_Indicator CC_Badge CC_Solution Region
00001 12111 X 44444
null 20200 X X X 44444
null 00001 X X 22222
null 32332 X 11111
null 44215 X X 11111
null 84425 X 33333
second effort, described as rudimentary below...
Select p.parent_program_id, p.program_id, p.name, p.copyright, p.active_flag,
max(decode(c.category_id,36261,'X','')) As CC_Indicator,
max(decode(c1.category_id,36362,'X','')) As CC_Badge,
max(decode(c2.category_id,43221,'X','')) As CC_Solution,
max(decode(c3.category_id,6321,'US','')) As US,
max(decode(c4.category_id,6081,'CA','')) As CA,
max(decode(c5.category_id,35061,'GS','')) As GS
From tbl_program p Join xref_category_program xcp On p.program_id=xcp.program_id
left Join tbl_category c On xcp.category_id=c.category_id and c.category_id = 36261
left Join tbl_category c1 On xcp.category_id=c1.category_id and c1.category_id = 36362
left Join tbl_category c2 On xcp.category_id=c2.category_id and c2.category_id = 43221
left Join tbl_category c3 On xcp.category_id=c3.category_id and c3.category_id = 6321
left Join tbl_category c4 On xcp.category_id=c4.category_id and c4.category_id = 6081
left Join tbl_category c5 On xcp.category_id=c5.category_id and c5.category_id = 35061
where xcp.category_id in(36261,36362,43221,6321,6081,35061)
group by p.program_id, p.name, p.copyright, p.active_flag, p.parent_program_id
Order by p.program_id
I think you can simplify your query a bit, as follows:
Select p.parent_program_id,
p.program_id,
p.name,
p.copyright,
p.active_flag,
max(decode(c.category_id,36261,'X','')) As CC_Indicator,
max(decode(c.category_id,36362,'X','')) As CC_Badge,
max(decode(c.category_id,43221,'X','')) As CC_Solution,
max(decode(c.category_id,6321, 'US','')) As US,
max(decode(c.category_id,6081, 'CA','')) As CA,
max(decode(c.category_id,35061,'GS','')) As GS
From tbl_program p
INNER Join xref_category_program xcp
On p.program_id = xcp.program_id
INNER Join tbl_category c
On xcp.category_id = c.category_id
where xcp.category_id in (36261, 36362, 43221, 6321, 6081, 35061)
group by p.program_id, p.name, p.copyright, p.active_flag, p.parent_program_id
Order by p.program_id
I don't think you need the multiple joins of TBL_CATEGORY - one should do it, as you're identifying which categories you want in the WHERE clause.
I'm still at something of a loss as to getting the region ID's in. It seems that most of the basic data for this query (PROGRAM_ID, etc) comes from TBL_PROGRAM. Is there a column on TBL_PROGRAM which identifies the region? You can always make a second join of XREF_CATEGORY_PROGRAM or TBL_CATEGORY, but without knowing what column in the other tables identifies the region I can't help you understand how to get the region data joined in.
Share and enjoy.

Sybase SQL - Remove "semi-duplicates" from query results

I have a query that uses two SELECT statements that are combined using a UNION ALL. Both statements pull data from similar tables to populate the query results. I am attempting to remove the "semi-duplicate" rows from the query, but am having issues doing so.
My query is the following:
SELECT DISTINCT *
FROM
(
SELECT
TeamNum = CASE
WHEN T.TeamName = 'Alpha Team'
THEN '1'
WHEN T.TeamName IN ('Bravo Team', 'Charlie Team')
THEN '2'
WHEN T.TeamName = 'Delta Team'
THEN '3'
ELSE '<Undefined>'
END,
P.PatientLastName AS LastName,
P.PatientFirstName AS FirstName,
R.PrimaryCity AS City,
ReimbursorName = CASE
WHEN RE.ReimbursorDescription = 'Medicare'
Then 'R1'
WHEN RE.ReimbursorDescription = 'Medicaid'
Then 'R2'
ELSE 'R3'
END,
P.PatientID AS PatientID
FROM
PatReferrals PR LEFT JOIN Patient P ON PR.PatientID = P.PatientID,
Patient P LEFT OUTER JOIN Rolodex R ON P.RolodexID = R.RolodexID,
PatReferrals PR LEFT OUTER JOIN PatReimbursors PRE ON PR.PatientID = PRE.PatientID,
PatReimbursors PRE LEFT OUTER JOIN Reimbursors RE ON PRE.ReimbursorID = RE.ReimbursorID,
PatReferrals PR FULL OUTER JOIN Teams T ON PR.TeamID = T.TeamID,
WHERE
PR.ReferralDate BETWEEN GETDATE()-4 AND GETDATE()-1
AND PR.Status <> 'R'
AND PRE.CoveragePriority = '1'
AND PRE.ExpirationDate IS NULL
UNION ALL
SELECT
TeamNum = CASE
WHEN T.TeamName = 'Alpha Team'
THEN '1'
WHEN T.TeamName IN ('Bravo Team', 'Charlie Team')
THEN '2'
WHEN T.TeamName = 'Delta Team'
THEN '3'
ELSE '<Undefined>'
END,
P.PatientLastName AS LastName,
P.PatientFirstName AS FirstName,
R.PrimaryCity AS City,
ReimbursorName = CASE
WHEN RE.ReimbursorDescription = 'Medicare'
Then 'E1'
WHEN RE.ReimbursorDescription = 'Medicaid'
Then 'E2'
ELSE 'E3'
END,
P.PatientID AS PatientID
FROM
PatReferrals PR LEFT JOIN Patient P ON PR.PatientID = P.PatientID,
Patient P LEFT OUTER JOIN Rolodex R ON P.RolodexID = R.RolodexID,
PatReferrals PR LEFT OUTER JOIN PatEligibilities PE ON PR.PatientID = PE.PatientID,
PatEligibilities PE LEFT OUTER JOIN Reimbursors RE ON PE.ReimbursorID = RE.ReimbursorID,
PatReferrals PR FULL OUTER JOIN Teams T ON PR.TeamID = T.TeamID,
WHERE
PR.ReferralDate BETWEEN GETDATE()-4 AND GETDATE()-1
AND PR.Status <> 'R'
AND PE.Status <> 'V'
AND PE.ApplicationDate BETWEEN DATE(PR.ReferralDate)-5 AND DATE('2100/01/01')
)
AS DUMMYTBL
ORDER BY
DUMMYTBL.LastName ASC,
DUMMYTBL.FirstName ASC
The results that I receive when I run the query is the following:
3 Doe Jane Town R1 19874
1 Roe John City R3 50016
1 Roe John City E1 50016
2 Smith Jane Town E3 33975
The data that I am needing to remove is duplicate rows based on a certain criteria once the results are brought in from the original query. Each person can only be listed once and they must have a single pay source (R1, R2, R3, E1, E2, E3). If there is a R#, than there cannot be a E# listed for that person. If there are no R#'s than an E# must be listed. As shown in my example results, line 2 and 3 have the same person listed, but two pay sources (R3 and E1).
How can I go about making each person have only one row shown using the criteria that I have listed?
EDIT: Modifed the SQL query to show the original variables from the WHERE clauses in order to show further detail on the query. The PatReimbursors and the PatEligibilities tables have similar data, but the criteria is different in order to pull the correct data.
Your query does not make sense. I would start by eliminating the implicit cartesian product, generated by the , in the from clause.
My guess is that the from clause should be:
FROM
PatReferrals PR LEFT JOIN
Patient P
ON PR.PatientID = P.PatientID left outer join
Rolodex R
ON P.RolodexID = R.RolodexID left outer join
PatEligibilities PE
ON PR.PatientID = PE.PatientID left outer join
Reimbursors RE
ON PE.ReimbursorID = RE.ReimbursorID left outer join
Teams T ON PR.TeamID = T.TeamID
Once you do this, you may not need the union all or the select distinct. You may be able to put both the reimbursors and the eligibilities in the same query.
Use a subquery or subqueries.
The overall query should be written using the following pattern:
Select Distinct [Person Data]
From PersonTable
left Join to otherTable1 -- add outer join for each table you need data from
On [Conditions that ensure join can generate only one row per person,
... and specify which of possibly many rows to get...]
Make sure the conditions eliminate any possibility for the join to generate more than one row from the other [outer] table per person row in in the person table,. This may (and often does) require that the join condition be based on a subquery, as, for example...
Select Distinct [Person Data]
From PersonTable p
left Join to employments e -- add outer join for each table you need data from
On e.PersonId = p.PersonId
and e.HireDate = (Select Max(hiredate) from employments
where personId = p.PersonId)
After working with this for quite some time today, I found a solution to the problem that I was having. Here is the solution that works and pulls the correct information that I was needing:
SELECT DISTINCT
TeamNum,
LastName,
FirstName,
City,
ReimbursorName = CASE
WHEN max(ReimbursorName) IN ('R1', 'E1')
THEN '1'
WHEN max(ReimbursorName) IN ('R2', 'E2')
THEN '2'
ELSE '3'
END,
PatientID
FROM
(
SELECT
TeamNum = CASE
WHEN T.TeamName = 'Alpha Team'
THEN '1'
WHEN T.TeamName IN ('Bravo Team', 'Charlie Team')
THEN '2'
WHEN T.TeamName = 'Delta Team'
THEN '3'
ELSE '<Undefined>'
END,
P.PatientLastName AS LastName,
P.PatientFirstName AS FirstName,
R.PrimaryCity AS City,
ReimbursorName = CASE
WHEN RE.ReimbursorDescription = 'Medicare'
Then 'R1'
WHEN RE.ReimbursorDescription = 'Medicaid'
Then 'R2'
ELSE 'R3'
END,
P.PatientID AS PatientID
FROM
PatReferrals PR LEFT JOIN Patient P ON PR.PatientID = P.PatientID,
Patient P LEFT OUTER JOIN Rolodex R ON P.RolodexID = R.RolodexID,
PatReferrals PR LEFT OUTER JOIN PatReimbursors PRE ON PR.PatientID = PRE.PatientID,
PatReimbursors PRE LEFT OUTER JOIN Reimbursors RE ON PRE.ReimbursorID = RE.ReimbursorID,
PatReferrals PR FULL OUTER JOIN Teams T ON PR.TeamID = T.TeamID
WHERE
PR.ReferralDate BETWEEN GETDATE()-4 AND GETDATE()-1
AND PR.Status <> 'R'
AND PRE.CoveragePriority = '1'
AND PRE.ExpirationDate IS NULL
UNION ALL
SELECT
TeamNum = CASE
WHEN T.TeamName = 'Alpha Team'
THEN '1'
WHEN T.TeamName IN ('Bravo Team', 'Charlie Team')
THEN '2'
WHEN T.TeamName = 'Delta Team'
THEN '3'
ELSE '<Undefined>'
END,
P.PatientLastName AS LastName,
P.PatientFirstName AS FirstName,
R.PrimaryCity AS City,
ReimbursorName = CASE
WHEN RE.ReimbursorDescription = 'Medicare'
Then 'E1'
WHEN RE.ReimbursorDescription = 'Medicaid'
Then 'E2'
ELSE 'E3'
END,
P.PatientID AS PatientID
FROM
PatReferrals PR LEFT JOIN Patient P ON PR.PatientID = P.PatientID,
Patient P LEFT OUTER JOIN Rolodex R ON P.RolodexID = R.RolodexID,
PatReferrals PR LEFT OUTER JOIN PatEligibilities PE ON PR.PatientID = PE.PatientID,
PatEligibilities PE LEFT OUTER JOIN Reimbursors RE ON PE.ReimbursorID = RE.ReimbursorID,
PatReferrals PR FULL OUTER JOIN Teams T ON PR.TeamID = T.TeamID
WHERE
PR.ReferralDate BETWEEN GETDATE()-4 AND GETDATE()-1
AND PR.Status <> 'R'
AND PE.Status <> 'V'
AND PE.ApplicationDate BETWEEN DATE(PR.ReferralDate)-5 AND DATE('2100/01/01')
)
AS DUMMYTBL
GROUP BY
TeamNum,
LastName,
FirstName,
City,
PatientID
ORDER BY
DUMMYTBL.LastName ASC,
DUMMYTBL.FirstName ASC
Thanks for all the responses that were provided.