Count function in a case statement - sql

I have the following query that counts members:
`SELECT
distinct count(cst_recno) AS [Member ID],
adr_country AS Country
FROM
mb_membership
JOIN mb_member_type on mbt_key = mbr_mbt_key
JOIN co_customer ON cst_key=mbr_cst_key and mbr_delete_flag =0 and
cst_delete_flag=0
LEFT JOIN co_individual ON cst_key=ind_cst_key and ind_delete_flag=0
LEFT JOIN co_customer_x_customer ON cxc_cst_key_1 = co_customer.cst_key and
(cxc_end_date is null or datediff(dd,getdate(),cxc_end_date) >=0) and
cxc_rlt_code='Chapter Member'
LEFT JOIN co_chapter ON cxc_cst_key_2=chp_cst_key
LEFT JOIN co_customer_x_address ON cst_cxa_key=cxa_key
LEFT JOIN co_address ON adr_key=cxa_adr_key
LEFT JOIN co_country on adr_country=cty_code
LEFT JOIN co_region on rgn_key=cty_rgn_key
LEFT JOIN vw_client_uli_member_type WITH (NOLOCK) ON cst_key=mem_cst_key
WHERE mbr_join_date >= '7/1/2015' and mbt_code not like '%Council%'
AND ind_int_code <> 'staff' and cst_org_name_dn not like '%urban land ins%'
and cst_eml_address_dn not like '%#uli.org'
and adr_country ='singapore'
group by adr_country`
and the query returns:
Member ID Country
145 Singapore
However, I know that it includes a few duplicates because when I take out a count function and don't have a group by clause it returns 140 distinct rows.
When I check why it includes a few dupes it is caused by one of the dates.
Can you advise? I basically want to run the query that will display 140 distinct count of Member ID:
Member ID Country
140 Singapore

Instead of SELECT distinct count(cst_recno)... use SELECT count(distinct cst_recno)...:
SELECT
count(distinct cst_recno) AS [Member ID],
adr_country AS Country
FROM
mb_membership
JOIN mb_member_type on mbt_key = mbr_mbt_key
JOIN co_customer ON cst_key=mbr_cst_key and mbr_delete_flag =0 and
cst_delete_flag=0
LEFT JOIN co_individual ON cst_key=ind_cst_key and ind_delete_flag=0
LEFT JOIN co_customer_x_customer ON cxc_cst_key_1 = co_customer.cst_key and
(cxc_end_date is null or datediff(dd,getdate(),cxc_end_date) >=0) and
cxc_rlt_code='Chapter Member'
LEFT JOIN co_chapter ON cxc_cst_key_2=chp_cst_key
LEFT JOIN co_customer_x_address ON cst_cxa_key=cxa_key
LEFT JOIN co_address ON adr_key=cxa_adr_key
LEFT JOIN co_country on adr_country=cty_code
LEFT JOIN co_region on rgn_key=cty_rgn_key
LEFT JOIN vw_client_uli_member_type WITH (NOLOCK) ON cst_key=mem_cst_key
WHERE mbr_join_date >= '7/1/2015' and mbt_code not like '%Council%'
AND ind_int_code <> 'staff' and cst_org_name_dn not like '%urban land ins%'
and cst_eml_address_dn not like '%#uli.org'
and adr_country ='singapore'
group by adr_country`

Related

Problem with where clause and count transactions?

I want to count how many transactions I have by Currency. When I count without a where clause I get 0 transactions where I have NULL values but when I use a where clause with an IN operator I get a filtered result and no zero results. How to show 0 in count transactions?
SELECT
c.ShortName,
count(ad.AccountId) as No_of_transactions
FROM Currency c
LEFT JOIN Account a ON c.id = a.CurrencyId
LEFT JOIN AccountDetails ad ON a.id = ad.AccountId
LEFT JOIN [Location] l ON ad.LocationId = l.Id
LEFT JOIN LocationType lt ON l.LocationTypeId = lt.Id
WHERE lt.Name IN('Region Branch', 'City Branch')
GROUP BY c.ShortName
This is the result that I want to get:
EUR 31,
USD 0,
GBR 0
You have a LEFT JOIN. The filtering needs to go in the ON clause:
SELECT c.ShortName,
COUNT(lt.id) as No_of_transactions
FROM Currency c LEFT JOIN
Account a
ON c.id = a.CurrencyId LEFT JOIN
AccountDetails ad
ON a.id = ad.AccountId LEFT JOIN
[Location] l
ON ad.LocationId = l.Id LEFT JOIN
LocationType lt
ON l.LocationTypeId = lt.Id AND
lt.Name IN ('Region Branch', 'City Branch')
GROUP BY c.ShortName;
In your version, the non-matches turn into NULLs, which the WHERE conditions filter out.
You want to move the condition on the left joined table from the where clause to the on clause of the relevant join to avoid records being filtered out when they do not exist in that table.
Also, I think that you need COUNT(DISTINCT ad.id) (as per the comments, a transaction is uniquely represented by this column):
SELECT
c.ShortName,
COUNT(DISTINCT ad.id) as No_of_transactions
FROM Currency c
LEFT JOIN Account a ON c.id = a.CurrencyId
LEFT JOIN AccountDetails ad ON a.id = ad.AccountId
LEFT JOIN [Location] l ON ad.LocationId = l.Id
LEFT JOIN LocationType lt ON l.LocationTypeId = lt.Id AND lt.Name IN('Region Branch', 'City Branch')
GROUP BY c.ShortName
SELECT
c.ShortName,
COUNT(t.Id) as No_of_transations
FROM Currency c
LEFT JOIN Account a ON c.id = a.CurrencyId
LEFT JOIN AccountDetails ad ON a.id = ad.AccountId
LEFT JOIN [Location] l ON ad.LocationId = l.Id
LEFT JOIN (SELECT * FROM LocationType lt WHERE lt.Name IN('Region Branch', 'City
Branch')) AS t ON l.LocationTypeId = t.Id
GROUP BY c.ShortName

SQL server Left join with child tables and get the table name

Let's assume we have a table Instrument with child tables Equity and Bond having a foreign key InstrumentId. Each instrument has a unique record in one of the child tables.
Is it possible to make a view using left joins to see all the instrument with a column containing the table name in which the record is present ?
SELECT Instrument.InstrumentId, Instrument.Name, ***CHILD_TABLE_NAME***
FROM Instrument
LEFT OUTER JOIN
Equity ON Equity.InstrumentId = Instrument.InstrumentId
LEFT OUTER JOIN
Bond ON SBond.InstrumentId = Instrument.InstrumentId
An alternative is to make an union of inner joins:
SELECT instrumentId, Name, instrumentType
FROM
(SELECT Instrument.instrumentId, Name, 'Equity' as instrumentType FROM dbo.Equity inner join Instrument on Instrument.InstrumentId = Equity.InstrumentId
UNION
SELECT Instrument.instrumentId, Name, 'Bond' as instrumentType from dbo.Bond inner join Instrument on Instrument.InstrumentId = Bond.InstrumentId) u
one option is to include the table name in your joins like this
SELECT i.InstrumentId,
i.Name,
e.TableEquity,
b.TableBond
FROM Instrument i
LEFT OUTER JOIN (select 'Equity' as TableEquity from Equity) e
ON i.InstrumentId = e.InstrumentId
LEFT OUTER JOIN (select 'Bond' as TableBond from Bond) b
ON i.InstrumentId = b.InstrumentId
EDIT by #sofsntp : to merge the Equity/Bond in one column
SELECT i.InstrumentId,
i.Name,
(ISNULL(e.TableEquity,'') + ISNULL(b.TableBond ,''))
FROM Instrument i
LEFT OUTER JOIN (select *, 'Equity' as TableEquity from Equity) e
ON e.InstrumentId = i.InstrumentId
LEFT OUTER JOIN (select *, 'Bond' as TableBond from StraightBond) b
ON b.InstrumentId = i.InstrumentId
Use a case expression:
SELECT i.InstrumentId, i.Name,
(CASE WHEN e.InstrumentId IS NOT NULL THEN 'Equity'
WHEN b.InstrumentId IS NOT NULL THEN 'Bond'
END) as which_table
FROM Instrument i LEFT OUTER JOIN
Equity e
ON e.InstrumentId = i.InstrumentId LEFT OUTER JOIN
Bond b
ON b.InstrumentId = i.InstrumentId ;
Note: This gives the first match. If you want both:
SELECT i.InstrumentId, i.Name,
((CASE WHEN e.InstrumentId IS NOT NULL THEN 'Equity' ELSE '' END) +
(CASE WHEN b.InstrumentId IS NOT NULL THEN 'Bond' ELSE '' END)
) as which_table
FROM Instrument i LEFT OUTER JOIN
Equity e
ON e.InstrumentId = i.InstrumentId LEFT OUTER JOIN
Bond b
ON b.InstrumentId = i.InstrumentId ;
EDIT
I am adding END which was missing

Conversion failed when converting the nvarchar value 'FALL' to data type int

I have a query below that I have been struggled with. I know that my evt_code column is integer but includes nvarchar value also (for example FALL2015,JP19200202 and many others including letters).
I need to include those nvarchar codes in my result set. Can you help? I believe I need to add a condition into my join in order to include those codes with nvarchar datatype but don't know how.
I apologize for such a long script. You may ignore it. The question is up here but wanted to include the query also. I am using SQL Server 2014.
select distinct
prc_code AS REGCLASS,
etp_code AS TYPE,
evt_title AS TITLE,
evt_code AS MEETING,
ea.adr_city AS CITY,
ea.adr_state AS STATE,
ea.adr_country AS COUNTRY,
evt_start_date AS DATE,
case
when net_ivd_amount_cp=0
then 'Comp'
else 'Paid'
end as 'Paid/Comp',
net_ivd_amount_cp as 'Revenue',
ev_registrant.reg_cst_key AS [COUNT],
net_ivd_amount_cp,
chp_name as 'District / National Council',
c03_region_name as 'DC Region',
cst_sort_name_dn as 'Name',
ind_first_name as 'First',
ind_last_name as 'Last',
cst_ixo_title_dn as 'Registrant Title',
cst_org_name_dn as 'Organization',
ca.adr_line1 as 'Address 1',
ca.adr_line2 as 'Address 2',
ca.adr_city as 'Registrant City',
ca.adr_state as 'Registrant State',
ca.adr_post_code as 'Registrant Zip',
ca.adr_country as 'Registrant Country',
cst_phn_number_complete_dn as 'Phone',
cst_eml_address_dn as 'Email',
case
when mem_member_type IS null
then 'Prospect'
else mem_member_type
end as 'Member/Prospect',
mem_join_date as 'Join Date',
reg_attendance_flag as 'Attended',
case
when ind_int_code='Student'
then 'Student'
else org_ogt_code
end as 'Industry',
cr.rgn_code as 'Region'
FROM ev_registrant
join co_customer on reg_cst_key=cst_key
INNER JOIN ev_event on reg_evt_key=evt_key
INNER JOIN ev_event_type ON ev_event.evt_etp_key = ev_event_type.etp_key
left outer join dbo.ac_invoice with (nolock) ON dbo.ev_registrant.reg_inv_code=dbo.ac_invoice.inv_code
LEFT OUTER JOIN dbo.vw_ac_invoice_detail WITH (nolock) ON dbo.ac_invoice.inv_key = net_inv_key
LEFT OUTER JOIN dbo.ac_payment_detail WITH (nolock) ON dbo.ac_payment_detail.pyd_ivd_key = net_ivd_key
LEFT OUTER JOIN dbo.oe_product with (nolock) on dbo.oe_product.prd_key=net_ivd_prc_prd_key
LEFT OUTER JOIN dbo.oe_product_type WITIH (nolock) on prd_ptp_key = ptp_key
LEFT OUTER JOIN dbo.oe_price WITH (nolock) on net_ivd_prc_key = prc_key
left outer join ev_event_location on evl_evt_key=evt_key and evl_primary=1
left outer join ev_location on evl_loc_key=loc_key
left outer join co_customer_x_address ecxa on loc_cxa_key=ecxa.cxa_key
left outer join co_address ea on ecxa.cxa_adr_key=ea.adr_key
left outer join client_uli_dc_region on LEFT(evt_code, 4)=c03_chp_chapter_number
left outer join co_chapter on LEFT(evt_code, 4)=chp_chapter_number
left outer join co_customer_x_address ccxa on cst_cxa_key=ccxa.cxa_key
left outer join co_address ca on ccxa.cxa_adr_key=ca.adr_key
LEFT OUTER JOIN co_country cc on ca.adr_country=cc.cty_code
LEFT OUTER JOIN co_region cr on cr.rgn_key=cc.cty_rgn_key
left outer join vw_client_uli_member_type on cst_key=mem_cst_key
left outer join co_individual_x_organization on ixo_key=cst_ixo_key
left outer join co_organization on ixo_org_cst_key=org_cst_key
left outer join co_individual on cst_key=ind_cst_key
where
((net_ivd_void_flag)=0
Or net_ivd_void_flag Is Null)
AND (reg_delete_flag=0 Or reg_delete_flag Is Null)
AND ((ev_registrant.reg_cancel_date) Is Null
and evt_start_date>='2017-07-01')
and ptp_code='event'
Ok, so now we know that the evt_code is of data type NVARCHAR.
You have two joins which are joining on that field, listed below.
left outer join client_uli_dc_region on LEFT(evt_code, 4)=c03_chp_chapter_number
left outer join co_chapter on LEFT(evt_code, 4)=chp_chapter_number
If either of those columns are of any numerical data type, you'll get the error which you have mentioned. The solution would be to CAST the fields which you join to them, to NVARCHAR

Need assistance with T-SQL query UNION, JOINS, COUNT

Looks that I am stumped with query to sum up shipments grouped by by union operator. Today I was working to retrieve total shipments (count(Distinct. U.SjipmentId) delivered by agent, driver (U.AgentCode) to particular country (U.CtryCode, U.CtryName). The last thing I would like to do is to sum all the shipments together to get the total amount of shipments.
Would anyone advise how I this can be achieved in easy and simply way?
Below you can find my most current query.
SELECT U.AgentCode, U.CtryCode, U.CtryName, count(distinct U.Id)
FROM (
select Agent.AgentCode, Addr.CtryCode, Ctry.Name, Ship.Id
from Shipment
LEFT JOIN RouteTab (nolock) ON RoutTbl.Cexp= Shipment.ID
LEFT JOIN Agent (NOLOCK) ON Agent.AgentID = RouteTbl.AgentID
LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
WHERE RouteTbl.Bur ='GB01' AND Agent.AgentCode IS NOT NULL
Union ALL
select Driver.DriverCode, Addr.CtryCode, Ctry.Name, Shipment.Id
from Shipment
LEFT JOIN RouteTab (nolock) ON RoutTbl.Cexp= Shipment.Id
LEFT JOIN Driver (NOLOCK) ON Driver.DriverId = RouteTbl.DriverId
LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
WHERE RouteTbl.Bur ='GB01' AND Driver.DriverCode IS NOT NULL
) as U
GROUP BY U.AgentCode, U.CtryCode, U.CtryName
ORDER BY U.AgentCode, U.CtryCode, U.CtryName
Union statements need to have the exact same column names, in your code below the Union All command, try this:
select Driver.DriverCode as AgentCode, Addr.CtryCode, Ctry.Name, Shipment.Id
Also change the Ctry.Name to Ctry.Name as CtryName in both your select statements.
You have the same code from your UNION. Good way to use WITH clause.
In your select you don't need a UNION - use a left join and COALESCE instead.
;With r_tab AS
(
select RouteTab.AgentID, Addr.CtryCode, Ctry.Name, Ship.Id,RouteTab.DriverId
from Shipment
LEFT JOIN RouteTab (nolock) ON RouteTab.Cexp= Shipment.ID
LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
WHERE RouteTab.Bur ='GB01'
)
SELECT COALESCE(Agent.AgentCode,Driver.DriverCode) AgentCode, U.AgentCode, U.CtryCode, U.CtryName,
count(distinct U.Id)
FROM r_tab U
LEFT JOIN Agent (NOLOCK) ON Agent.AgentID = U.AgentID
AND Agent.AgentCode IS NOT NULL
LEFT JOIN Driver (NOLOCK) ON Driver.DriverId = U.DriverId
AND Driver.DriverCode IS NOT NULL
GROUP BY COALESCE(Agent.AgentCode,Driver.DriverCode), U.CtryCode, U.CtryName
ORDER BY U.AgentCode, U.CtryCode, U.CtryName`enter code here`

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.