ALTER FUNCTION [dbo].[fCaseLoadRU](@agencyId bigint, @PersonnelId bigint = null, @ReportingUnit varchar(40) = null)
RETURNS TABLE
AS
RETURN (
SELECT ID as ClientID, ProviderNumber,
CASE WHEN a.RUCount = 1 THEN ProviderNumber ELSE 'YES: ' + CAST(a.RUCount AS VARCHAR(10))END as RUCount
FROM
( SELECT c.ID, RUCount= COUNT(*), ProviderNumber = MAX(e.ReportingUnit)
FROM Clients c
INNER JOIN Episodes e ON(c.ID = e.client_id)
LEFT JOIN ru repUnit ON(e.eRuId= repUnit.id)
INNER JOIN (SELECT * FROM UnitAllocation WHERE [PersonnelId] = @PersonnelId AND AccessToClientData =1) ua ON ReportingUnitID = repUnit.ID
LEFT JOIN (select * from fDischargeClientActive(@agencyId)) as dc ON (EpisodeID = e.episode_id)
WHERE c.agencyid = @agencyId
AND repUnit.reportingunit = ISNULL(@ReportingUnit, repUnit.reportingunit)
GROUP BY c.ID
UNION ALL
SELECT c.ID, RUCount= COUNT(*), ProviderNumber = MAX(e.ReportingUnit)
FROM Clients c
INNER JOIN Episodes e ON(c.ID = e.client_id)
LEFT JOIN ru repUnit ON(e.eRuId= repUnit.id)
WHERE c.agencyid = @agencyId AND c.TempClinicianID = @PersonnelId
AND repUnit.reportingunit = ISNULL(@ReportingUnit, repUnit.reportingunit)
GROUP BY c.ID
)a
)
|