Condensing duplicate data while maintaining multiple entries per client - sql

I apologize if the title is not descriptive enough. I am having a hard time describing what I am looking for.
I understand this is normally done on the front end but a client is requesting to have this data displayed in this way. this should show a single column with client information (lastname, firstname) and any/all booked appointments. Since there may be more than one appointment per client duplicate data will be displayed along each line. That will look like this:
lastName | firstName | apptDate | myStartTime | myEndTime
smith..............| john................| 4/7/2016........| 7:00.........................| 8:00
smith..............| john................| 4/9/2016........| 6:00.........................| 7:00
smith..............| john................| 4/14/2016......| 10:00.......................| 11:00
arnold.............| williams..........| 4/10/2016......| 7:00.........................| 11:00
arnold.............| williams..........| 4/11/2016......| 8:00.........................| 12:00
but I would like that to be displayed as:
smith..............| john................| 4/7/2016........| 7:00.........................| 8:00
................................................| 4/9/2016........| 6:00.........................| 7:00
................................................| 4/14/2016......| 10:00.......................| 11:00
arnold..............| williams.........| 4/10/2016.......| 7:00.........................| 11:00
................................................| 4/11/2016.......| 8:00.........................| 12:00
This is what I am currently working with:
SELECT
CASE
WHEN cli.rownum = 1 THEN cli.clientID
END AS 'clientID'
,CASE
WHEN cli.rownum = 1 THEN cli.lastName
END AS 'lastName'
,CASE
WHEN cli.rownum = 1 THEN cli.firstName
END AS 'firstName'
,CASE
WHEN cli.rownum = 1 THEN cli.homePhone
END AS 'home'
,CASE
WHEN cli.rownum = 1 THEN cli.cellPhone
END AS 'cell'
,info.*
,CASE
WHEN cli.rownum = 1 THEN cli.staffAlertMsg
END AS 'alert'
,cli.notes AS 'notes'
,CONVERT(varchar(10),cli.classDate,101) AS 'date'
,cli.myStartTime AS 'start'
,cli.myEndTime AS 'end'
,cli.typeName AS 'appointment'
FROM
(SELECT
c.clientID
,c.lastName
,c.firstName
,c.homePhone
,c.cellPhone
,info.*
,r.notes
,c.staffAlertMsg
,r.ClassDate
,r.myStartTime
,r.myEndTime
,vt.TypeName
,ROW_NUMBER()
OVER(PARTITION BY c.clientID ORDER BY c.clientID) AS 'rownum'
FROM clients c
LEFT OUTER JOIN tblReservation r
ON c.clientID = r.clientID
LEFT OUTER JOIN tblVisitTypes vt
ON vt.TypeID = r.visitType
OUTER APPLY
(SELECT
max(CASE
WHEN civ.clientIndexID = 4
THEN civ.clientIndexValueName
END) AS 'priority'
,max(CASE
WHEN civ.clientIndexID = 5
THEN civ.clientIndexValueName
END) AS 'lang'
,max(CASE
WHEN civ.clientIndexID = 17
THEN civ.clientIndexValueName
END) AS 'inter'
,max(CASE
WHEN ccf.name LIKE 'prac'
THEN ccv.TextVal
END) AS 'prac'
,max(CASE
WHEN st.TypeID = 100000001 THEN st.typeName
END) AS 'ride?'
,max(CASE
WHEN st.typeID = 100000006 THEN st.typeName
END) AS 'l?'
FROM tblClientCustomValues ccv
INNER JOIN tblClientCustomFields ccf
ON ccv.ID = ccf.ID
INNER JOIN tblClientIndexData cid
ON ccv.clientID = cid.clientID
INNER JOIN tblClientIndexValue civ
ON cid.clientIndexValueID = civ.clientIndexValueID
LEFT JOIN [type details] td
ON ccv.clientID = td.clientID
LEFT JOIN [student types] st
ON td.typeID = st.typeID
WHERE c.clientID = ccv.clientID
) info
) cli
WHERE cli.clientID != '-2'
AND cli.clientID != '0'
AND cli.clientID != '1'
AND (cli.classDate >= '4/1/2016'
AND cli.classDate <= '4/30/2016')

Assuming you want to only return the name for the first row of each client then this should work (also assuming a primary key column of ID on the clients table):
SELECT CASE WHEN cli.rownum = 1 THEN cli.lastName END AS lastName
,CASE WHEN cli.rownum = 1 THEN cli.firstName END AS firstName
,CONVERT(varchar(10),cli.apptDate,101) AS 'apptDate'
,cli.myStartTime
,cli.myEndTime
FROM
(SELECT c.ID
,c.lastName
,c.firstName
,r.apptDate
,r.myStartTime
,r.myEndTime
,ROW_NUMBER() OVER (PARTITION BY c.ID ORDER BY c.ID, r.apptDate, r.myStartTime) as rownum
FROM clients c
LEFT OUTER JOIN tblReservation r
ON c.clientID = r.clientID
LEFT OUTER JOIN tblVisitTypes vt
ON vt.TypeID = r.VisitType)
cli
ORDER BY cli.ID, cli.rownum
I have made both the join LEFT OUTER JOINS as your second INNER JOIN would have made the first join an INNER, which I assume is not what you wanted.

Related

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= orwhen the subquery is used as an expression

I am having this error message. I have tried many other ways but can't resolve the issue.
I would be really grateful if someone could look at this :
;WITH progression
AS
(
SELECT
w.CustomerID,
CASE WHEN SUM(CASE WHEN w.workflowoutcomeid = 8 THEN 1 ELSE 0 END) > 0 THEN 'Yes' ELSE 'No' END AS [PG01],
CASE WHEN SUM(CASE WHEN w.workflowoutcomeid = 11 THEN 1 ELSE 0 END) > 0 THEN 'Yes' ELSE 'No' END AS [PG03],
CASE WHEN SUM(CASE WHEN w.workflowoutcomeid = 14 THEN 1 ELSE 0 END) > 0 THEN 'Yes' ELSE 'No' END AS [PG04],
CASE WHEN SUM(CASE WHEN w.workflowoutcomeid = 17 THEN 1 ELSE 0 END) > 0 THEN 'Yes' ELSE 'No' END AS [PG05],
CASE WHEN SUM(CASE WHEN w.workflowoutcomeid = 9 THEN 1 ELSE 0 END) > 0 THEN 'Yes' ELSE 'No' END AS [in_work_review]
FROM
ABC.dbo.tblWorkflow w
WHERE
w.Deleted IS NULL
AND
w.workflowqueueid = 4
AND
w.workflowoutcomeid IN (8, 11, 14, 17, 9)
GROUP BY
w.CustomerID
),
contact_data
AS
(
SELECT
CustomerID, [Email], [Mobile], [Home]
FROM
(
SELECT
CustomerID,
CASE
WHEN ContactTypeID = 1 THEN 'Home'
WHEN ContactTypeID = 2 THEN 'Mobile'
WHEN ContactTypeID = 5 THEN 'Email'
END AS ContactTypeDescription,
ContactValue
FROM ABC.dbo.tblCustomerContact
WHERE ContactTypeID IN (1,2,5)
) base
PIVOT
(
MAX(ContactValue) FOR ContactTypeDescription IN ([Home],[Mobile],[Email])
) pvt
),
appointment
AS
(
SELECT
n.[Key] AS CustomerID,
MAX(CASE WHEN n.AppointmentStatusID IN (2,4) THEN n.ActionDate ELSE NULL END) AS [Last_Completed_Attended_Appointment],
MAX(CASE WHEN n.AppointmentStatusID = 1 THEN n.ActionDate ELSE NULL END) AS [Next Pending Appointment]
FROM ABC.dbo.tblNote n
WHERE n.AppointmentTypeID = 6 AND n.AppointmentStatusID IN (1,2,4)
GROUP BY n.[Key]
)
SELECT
m.Firstname + ' ' + m.Lastname AS [Manager],
u.Firstname + ' ' + u.Lastname AS [Adviser],
c.CustomerID,
c.GivenName + ' ' + c.FamilyName AS [Customer Name],
g.Gender,
e.EthnicityName AS Ethnicity,
com.CompanyName,
NULL AS DeliverySite,
d.[Name] AS District,
css.ServiceStatus,
contact_data.Email,
uad.Line1 AS AddressLine1,
uad.Line2 AS AddressLine2,
uad.Line3 AS AddressLine3,
uad.Postcode,
uad.AlternativePostcode,
uad.Town,
ISNULL(contact_data.mobile, contact_data.home) AS Phone,
c.StartDate,
(SELECT MIN(wh.MGCReviewerModifiedDate) AS [ST01_Approved_Date]
FROM ABC.dbo.tblWorkflow w
INNER JOIN ABC.dbo.tblWorkflowHistory wh
ON w.WorkflowID = wh.WorkflowID
WHERE wh.WorkflowQueueID = 4 AND wh.MGCReviewerModifiedDate IS NOT NULL
AND wh.Deleted IS NULL AND w.WorkflowOutcomeID = 1 AND w.WorkflowQueueID = 4
AND w.Deleted IS NULL AND w.CustomerID = c.CustomerID
GROUP BY w.WorkflowID, w.CustomerID) AS ST01_Approved_Date,
qual.LearningAimTitle,
qual.LearningAimCompletionStatus,
qual.LearningAimOutcomeStatus,
mwp.WorkExperienceTitle ,
mwp.WorkExperienceStartDate,
mwp.WorkExperienceEndDate,
mwp.learningaimcompletionstatus as [Work_Ex_CompletionStatus],
mwp.learningaimoutcomestatus as [Work_Ex_OutcomeStatus],
p.PG01 AS [PG01_Start(Job Start Approved/Claimed ?)],
p.in_work_review AS [PG01_In_work_review(Job Outcome Approved/Claimed ?)],
p.PG03 AS [PG03 – Education Approved / Claimed?],
p.PG04 AS [PG04 – Apprenticeship Approved / Claimed?],
p.PG05 AS [PG05– Apprenticeship Approved / Claimed?],
a.Last_Completed_Attended_Appointment,
a.[Next Pending Appointment],
FLOOR(DATEDIFF(day, c.DateOfBirth, GETDATE()) / 365.25) as CustomerAge
FROM ABC.dbo.tblCustomer c
LEFT JOIN ABC.dbo.tblUser u ON c.OwnerID = u.UserID
LEFT JOIN ABC.dbo.tblUser m ON u.ManagerID = m.UserID
LEFT JOIN ABC.dbo.tlkpGender g ON c.GenderID = g.GenderID
LEFT JOIN ABC.dbo.tlkpEthnicity e ON c.EthnicityID = e.EthnicityID
LEFT JOIN ABC.dbo.tblCompany com ON c.CompanyId = com.[CompanyID]
LEFT JOIN ABC.dbo.tblCustomerAddress cad ON c.CustomerID = cad.CustomerID AND cad.EffectiveTo IS NULL
LEFT JOIN ABC.dbo.tblUKAddress uad ON uad.UKaddressID = cad.UKaddressID
LEFT JOIN PostcodeESyNCS.dbo.tblPostcode po ON uad.Postcode = po.Postcode
LEFT JOIN PostcodeESyNCS.dbo.tlkpDistrict d ON po.DistrictId = d.DistrictId
LEFT JOIN ABC.dbo.tlkpCustomerServiceStatus css ON c.CustomerServiceStatusID = css.CustomerServiceStatusID
LEFT JOIN progression p ON c.CustomerID = p.CustomerID
LEFT JOIN contact_data ON c.CustomerID = contact_data.CustomerID
OUTER APPLY
(
SELECT TOP 1
l.learningaimid,
aim.LearningAimTitle,
aim.isfullqualification,
st.LearningAimCompletionStatus,
aos.LearningAimOutcomeStatus
FROM ABC.dbo.tbllearning l
LEFT JOIN ABC.dbo.tlkplearningaim aim on aim.learningaimid = l.learningaimid
LEFT JOIN ABC.dbo.tlkplearningaimcompletionstatus st on st.learningaimcompletionstatusid = l.learningaimcompletionstatusid
LEFT JOIN ABC.dbo.tlkpLearningAimOutcomeStatus aos on aos.learningaimoutcomestatusid = l.learningaimoutcomestatusid
WHERE aim.learningaimtypeid = 1 AND l.customerid = c.customerid
ORDER BY l.StartDate DESC
) qual
OUTER APPLY
(
SELECT TOP 1
l.learningaimid,
REPLACE(aim.LearningAimTitle,',',' ') as WorkExperienceTitle,
aim.isfullqualification,
st.LearningAimCompletionStatus,
outcome.LearningAimOutcomeStatus,
l.StartDate as WorkExperienceStartDate,
l.ActualEndDate as WorkExperienceEndDate
FROM ABC.dbo.tbllearning l
LEFT JOIN ABC.dbo.tlkplearningaim aim ON aim.learningaimid=l.learningaimid
LEFT JOIN ABC.dbo.tlkplearningaimcompletionstatus st ON st.learningaimcompletionstatusid=l.learningaimcompletionstatusid
LEFT JOIN ABC.dbo.tlkpLearningAimOutcomeStatus outcome ON outcome.learningaimoutcomestatusid= l.learningaimoutcomestatusid
WHERE aim.LearningAimID IN (SELECT la.LearningAimID
FROM ABC.dbo.tlkpLearningAim la
WHERE la.LearningAimTypeID = 2
and la.LearningAimTitle like '%Work%')
AND l.customerid = c.customerid
ORDER BY StartDate DESC
) AS mwp
LEFT JOIN appointment a ON c.CustomerID = a.CustomerID
WHERE
c.Deleted IS NULL
I am getting the following error:
Msg 512, Level 16, State 1, Line 2
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Warning: Null value is eliminated by an aggregate or other SET operation.
The only place where I see that this could be happening is the definition of ST01_Approved_Date:
(SELECT MIN(wh.MGCReviewerModifiedDate) AS [ST01_Approved_Date]
FROM ABC.dbo.tblWorkflow w JOIN
ABC.dbo.tblWorkflowHistory wh
ON w.WorkflowID = wh.WorkflowID
WHERE wh.WorkflowQueueID = 4 AND wh.MGCReviewerModifiedDate IS NOT NULL AND
wh.Deleted IS NULL AND w.WorkflowOutcomeID = 1 AND w.WorkflowQueueID = 4 AND
w.Deleted IS NULL AND w.CustomerID = c.CustomerID
GROUP BY w.WorkflowID, w.CustomerID
) AS ST01_Approved_Date,
A correlated subquery should not contain GROUP By for exactly this reason. I don't know what the logic would be, but there should probably be a condition on w.WorkFlowId to the outer query, something like:
(SELECT MIN(wh.MGCReviewerModifiedDate) AS [ST01_Approved_Date]
FROM ABC.dbo.tblWorkflow w JOIN
ABC.dbo.tblWorkflowHistory wh
ON w.WorkflowID = wh.WorkflowID
WHERE wh.WorkflowQueueID = 4 AND wh.MGCReviewerModifiedDate IS NOT NULL AND
wh.Deleted IS NULL AND w.WorkflowOutcomeID = 1 AND w.WorkflowQueueID = 4 AND
w.Deleted IS NULL AND w.CustomerID = c.CustomerID AND
w.workflowID = <outer query reference>.WorkflowId
) AS ST01_Approved_Date,

Get minimum value per user

I have this SQL code here, my wish is to calculate the latest fee balance per student for each deposit made. So far I have been able to achieve this but now the question is how I'm I to select only the latest balance while disregarding the other previous entries/Balances
(select
f.Totals -SUM(Total) OVER(ORDER BY pay_Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Balance,
p.Total as 'TotalPaid',
c.class_id as 'ClassID',
p.std_ID as 'STDID',
c.class_name as 'Class',
a.ad_stdname as 'Name',
t.term_id as 'TermID',
t.term_name as 'Term',
p.Date as 'Date',
case when (st.str_id = null) then '-' else st.str_id end as 'StrID',
case when (p.Tution_fee = null) then '0' else p.Tution_fee end as 'Tution',
case when (p.adm_fee = null) then '0' else p.adm_fee end as 'Admission',
case when (p.Activity_fee = null) then '0' else p.Activity_fee end as 'Activity',
case when (p.Textbk_Statio = null) then '0' else p.Textbk_Statio end as 'Texbooks',
case when (p.Transport_fee = null) then '0' else p.Transport_fee end as 'Transport'
from Payments p
inner join Admissions a
on a.ad_id = p.std_ID
inner join classes c
on c.class_id =p.class_id
inner join fees f on f.fee_classID = p.class_id and f.Term_id = p.Term_id
left join streams st
on st.str_id = p.str_id
inner join terms t
on p.Term_id = t.term_id
where a.ad_id = 29
)
order by p.std_name,Balance,p.Date desc
This is my current output
I have selected min value for each user in below example:
user date value
Sonu 1/2/2010 1.5
Monu 1/3/2010 2.5
Arun 8/4/2009 3.5
Sonu 2/2/2010 1.0
Monu 12/2/2009 0.5
select t.username, t.date, t.value
from MyTable t
inner join (
select username, min(value) as value
from MyTable
group by username
) tm on t.username = tm.username and t.value = tm.value
Demo sql Fiddle
Use above logic to implement in your code
I tried to accommodate above logic in you query. for now i have just used stdid for grouping, you may add more accordingly. you might get some syntax error:
with MyTable as (select
f.Totals -SUM(Total) OVER(ORDER BY pay_Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Balance,
p.Total as 'TotalPaid',
c.class_id as 'ClassID',
p.std_ID as 'STDID',
c.class_name as 'Class',
a.ad_stdname as 'Name',
t.term_id as 'TermID',
t.term_name as 'Term',
p.Date as 'Date',
case when (st.str_id = null) then '-' else st.str_id end as 'StrID',
case when (p.Tution_fee = null) then '0' else p.Tution_fee end as 'Tution',
case when (p.adm_fee = null) then '0' else p.adm_fee end as 'Admission',
case when (p.Activity_fee = null) then '0' else p.Activity_fee end as 'Activity',
case when (p.Textbk_Statio = null) then '0' else p.Textbk_Statio end as 'Texbooks',
case when (p.Transport_fee = null) then '0' else p.Transport_fee end as 'Transport'
from Payments p
inner join Admissions a
on a.ad_id = p.std_ID
inner join classes c
on c.class_id =p.class_id
inner join fees f on f.fee_classID = p.class_id and f.Term_id = p.Term_id
left join streams st
on st.str_id = p.str_id
inner join terms t
on p.Term_id = t.term_id
where a.ad_id = 29
order by p.std_name,Balance,p.Date desc) select * from MyTable
inner join
(
select STDID, min(Balance) as value
from MyTable
group by STDID
) tm on t.STDID = tm.STDID and t.Balance = tm.Balance

Query to return record value in column instead of row?

I need assistance in creating a query. I have Client table that has unique client info - identified by their unique ClientID. I also have a Client_UserDefinedFields table that contains values of custom data for clients. They are linked via the ClientID and there may be many records for a ClientID in this Client_UserDefinedFields table.
My situation is that there are 3 custom data fields that I need to know the values for a given client (as shown by my CASE statement). My current query is bringing back the client 3 times (a row for each value) and I want to only see the client once (one row) and have these values shown as columns. Not sure if this is possible or how to that. Furthermore, when I tried using a CASE statement in my select, I cannot use AS 'fieldname' to identify it - since it's giving me an error on the AS keyword.
An example of my current SQL SELECT statement
SELECT
c.ClientID
, c.LastName
, c.FirstName
, c.MiddleName
, CASE WHEN cudf.UserDefinedFieldFormatULink = '93fb3820-38aa-4655-8aad-a8dce8aede' THEN cudf.UDF_ReportValue --AS 'DA Status'
WHEN cudf.UserDefinedFieldFormatULink = '2144a742-08c5-4c96-b9e4-d6f1f56c76' THEN cudf.UDF_ReportValue --AS 'FHAP Status'
WHEN cudf.UserDefinedFieldFormatULink = 'c3d29be9-af58-4241-a02d-9ae9b43ffa' THEN cudf.UDF_ReportValue --AS 'HCRA Status'
END
FROM Client_Program cp
INNER JOIN client c ON c.ulink = cp.clientulink
INNER JOIN code_program p ON p.ulink = cp.programulink
INNER JOIN Code_System_State css ON c.ContactMailingStateUlink = css.ulink
INNER JOIN Code_ClientStatus ccs ON c.ClientStatusULink = ccs.ULink
INNER JOIN Client_UserDefinedField cudf ON c.ULink = cudf.ClientULink
AND cp.ProgramStatusULink = '1' -- Open (active) program
AND c.ClientStatusULink = '10000000' --Active client
AND cp.programulink in ('7280f4a7-cd94-49be-86ad-a74421ff6f',
'0a9b94a3-edd7-4918-b79c-bf2b20f9da',
'54f6c691-2eba-49e5-8380-85f5349bca',
'ed8c497d-d4fe-41d7-a218-4235fd0734',
'5be826f0-b3c3-4ebe-871d-4d20b56da5')
AND cudf.UserDefinedFieldFormatULink IN ('93fb3820-38aa-4655-8aad-a8dce8aede', -- DA Status
'2144a742-08c5-4c96-b9e4-d6f1f56c76', --FHAP Status
'c3d29be9-af58-4241-a02d-9ae9b43ffa') --HCRA Status
Again, my issue is that I don't want to bring back the same client multiple times if they had more than one entry in the Client_UserDefinedFields table. I'd like to bring this in one row with each "Status" field correctly populated as a columns. How do I do this? Here's a sample of my current output:
ClientID LastName FirstName MiddleName PCHP/HCH Status DA Status FHAP Status HCRA Status
XXXXXXXXXXXX River Mike Allan Active (null) - None Selected - (null)
XXXXXXXXXXXX River Mike Allan Active Active (null) (null)
XXXXXXXXXXXX River Mike Allan Active (null) (null) - None Selected -
Ultimately would like to see just the one record with all the values
ClientID LastName FirstName MiddleName PCHP/HCH Status DA Status FHAP Status HCRA Status
XXXXXXXXXXXX River Mike Allan Active Active - None Selected - - None Selected -
Examples are very helpful as I'm not a SQL guru. Thank you!
SELECT c.ClientID,
c.LastName,
c.FirstName,
c.MiddleName,
CASE
WHEN cudf.UserDefinedFieldFormatULink = '93fb3820-38aa-4655-8aad-a8dce8aede' THEN
cudf.UDF_ReportValue AS 'DA Status'
WHEN cudf.UserDefinedFieldFormatULink = '2144a742-08c5-4c96-b9e4-d6f1f56c76' THEN
cudf.UDF_ReportValue AS 'FHAP Status'
WHEN cudf.UserDefinedFieldFormatULink = 'c3d29be9-af58-4241-a02d-9ae9b43ffa' THEN
cudf.UDF_ReportValue AS 'HCRA Status'
END
INTO #Temp
FROM Client_Program cp
INNER JOIN client c
ON c.ulink = cp.clientulink
INNER JOIN code_program p
ON p.ulink = cp.programulink
INNER JOIN Code_System_State css
ON c.ContactMailingStateUlink = css.ulink
INNER JOIN Code_ClientStatus ccs
ON c.ClientStatusULink = ccs.ULink
INNER JOIN Client_UserDefinedField cudf
ON c.ULink = cudf.ClientULink
AND cp.ProgramStatusULink = '1' -- Open (active) program
AND c.ClientStatusULink = '10000000' --Active client
AND cp.programulink IN ( '7280f4a7-cd94-49be-86ad-a74421ff6f', '0a9b94a3-edd7-4918-b79c-bf2b20f9da',
'54f6c691-2eba-49e5-8380-85f5349bca', 'ed8c497d-d4fe-41d7-a218-4235fd0734',
'5be826f0-b3c3-4ebe-871d-4d20b56da5'
)
AND cudf.UserDefinedFieldFormatULink IN ( '93fb3820-38aa-4655-8aad-a8dce8aede', -- DA Status
'2144a742-08c5-4c96-b9e4-d6f1f56c76'
); --FHAP Status
SELECT COALESCE(A.CilentID, B.ClientID, C.ClientID),LastName,
FirstName, MiddleName, [DA Status], [FHAP Status], [HCRA Status] FROM
(SELECT ClientID, LastName, FirstName, [DA Status] FROM #Temp WHERE [DA Status] IS NOT NULL) AS A FULL OUTER JOIN
(SELECT ClientID, LastName, FirstName, [FHAP Status] FROM #Temp WHERE [FHAP Status] IS NOT NULL) AS B ON A.ClientID = B.ClientID FULL OUTER JOIN
(SELECT ClientID, LastName, FirstName, [HCRA Status] FROM #Temp WHERE [HCRA Status] IS NOT NULL) AS C ON C.ClientID = A.ClientID
This is untested code - but the PIVOT command would work:
SELECT
c.ClientID
, c.LastName
, c.FirstName
, c.MiddleName
, CASE WHEN cudf.UserDefinedFieldFormatULink = '93fb3820-38aa-4655-8aad-a8dce8aede' THEN cudf.UDF_ReportValue --AS 'DA Status'
WHEN cudf.UserDefinedFieldFormatULink = '2144a742-08c5-4c96-b9e4-d6f1f56c76' THEN cudf.UDF_ReportValue --AS 'FHAP Status'
WHEN cudf.UserDefinedFieldFormatULink = 'c3d29be9-af58-4241-a02d-9ae9b43ffa' THEN cudf.UDF_ReportValue --AS 'HCRA Status'
END
FROM Client_Program cp
INNER JOIN code_program p ON p.ulink = cp.programulink
INNER JOIN Code_System_State css ON c.ContactMailingStateUlink = css.ulink
INNER JOIN Code_ClientStatus ccs ON c.ClientStatusULink = ccs.ULink
INNER JOIN client c ON c.ulink = cp.clientulink
INNER JOIN (
select *
from ( select ClientULink, UserDefinedFieldFormatULink , ROW_NUMBER() OVER (PARTITION BY ClientULink ORDER BY (SELECT NULL)) RN
from Client_UserDefinedField
where UserDefinedFieldFormatULink IN ('93fb3820-38aa-4655-8aad-a8dce8aede', -- DA Status
'2144a742-08c5-4c96-b9e4-d6f1f56c76')--FHAP Status
) as c
PIVOT (
MAX(UserDefinedFieldFormatULink) FOR RN IN ([1],[2],[3])
) as pvt
) cudf ON c.ULink = cudf.ClientULink
AND cp.ProgramStatusULink = '1' -- Open (active) program
AND c.ClientStatusULink = '10000000' --Active client
AND cp.programulink in ('7280f4a7-cd94-49be-86ad-a74421ff6f',
'0a9b94a3-edd7-4918-b79c-bf2b20f9da',
'54f6c691-2eba-49e5-8380-85f5349bca',
'ed8c497d-d4fe-41d7-a218-4235fd0734',
'5be826f0-b3c3-4ebe-871d-4d20b56da5')
If I understood your problem correctly then from my side below is the solution
SELECT DISTINCT
c.ClientID
, c.LastName
, c.FirstName
, c.MiddleName
, (CASE WHEN cudf.UserDefinedFieldFormatULink = '93fb3820-38aa-4655-8aad-a8dce8aede' THEN cudf.UDF_ReportValue ELSE NULL END) AS 'DA Status'
,(CASE WHEN cudf.UserDefinedFieldFormatULink = '2144a742-08c5-4c96-b9e4-d6f1f56c76' THEN cudf.UDF_ReportValue ELSE NULL END) AS 'FHAP Status'
,(CASE WHEN cudf.UserDefinedFieldFormatULink = 'c3d29be9-af58-4241-a02d-9ae9b43ffa' THEN cudf.UDF_ReportValue ELSE NULL END) AS 'HCRA Status'
FROM Client_Program cp
INNER JOIN client c ON c.ulink = cp.clientulink
INNER JOIN code_program p ON p.ulink = cp.programulink
INNER JOIN Code_System_State css ON c.ContactMailingStateUlink = css.ulink
INNER JOIN Code_ClientStatus ccs ON c.ClientStatusULink = ccs.ULink
INNER JOIN Client_UserDefinedField cudf ON c.ULink = cudf.ClientULink
AND cp.ProgramStatusULink = '1' -- Open (active) program
AND c.ClientStatusULink = '10000000' --Active client
AND cp.programulink in ('7280f4a7-cd94-49be-86ad-a74421ff6f',
'0a9b94a3-edd7-4918-b79c-bf2b20f9da',
'54f6c691-2eba-49e5-8380-85f5349bca',
'ed8c497d-d4fe-41d7-a218-4235fd0734',
'5be826f0-b3c3-4ebe-871d-4d20b56da5')
AND cudf.UserDefinedFieldFormatULink IN ('93fb3820-38aa-4655-8aad-a8dce8aede', -- DA Status
'2144a742-08c5-4c96-b9e4-d6f1f56c76')--FHAP Status

I need to pull unique patients that meet certain criteria

I pulled person_nbrs that have never had an EventType1 before or after an EventType2. I need to pull person_nbrs that have not had an EventType1 prior to having an EventType2. If they had an EventType1 after an EventType2, than it is to be ignored. Here is my query that pulls person_nbrs that have never had an EventType1 before or after EventType2.
SELECT
person_nbr, enc_nbr, enc_timestamp
FROM
person p
JOIN
patient_encounter pe ON p.person_id = pe.person_id
JOIN
patient_procedure pp ON pe.enc_id = pp.enc_id
WHERE
enc_timestamp >= '20170101'
--EventType2
AND code_id LIKE '2'
-- EventType1
AND person_nbr NOT IN (SELECT person_nbr
FROM person p
JOIN patient_encounter pe ON p.person_id = pe.person_id
JOIN patient_procedure pp ON pe.enc_id = pp.enc_id
WHERE code_id LIKE '1')
GROUP BY
person_nbr, enc_nbr, enc_timestamp
ORDER BY
person_nbr ;
You can do this with aggregation and a HAVING clause:
SELECT p.person_nbr
FROM person p JOIN
patient_encounter pe
ON p.person_id = pe.person_id JOIN
patient_procedure pp
ON pe.enc_id = pp.enc_id
GROUP BY p.person_nbr
HAVING SUM(CASE WHEN pp.code_id = 2 THEN 1 ELSE 0 END) > 0 AND -- has code 2
(MAX(CASE WHEN pp.code_id = 1 THEN pe.timestamp END) IS NULL OR
MAX(CASE WHEN pp.code_id = 1 THEN pe.timestamp END) < MIN(CASE WHEN pp.code_id = 2 THEN pe.timestamp END)
) ;
The HAVING clause has two parts:
The first specifies that the person has a code = 2.
The second specifies one of two conditions. The first is that there is no code = 1. The second alternative is that the latest c = 1 timestamp is less than the earliest code = 2 timestamp.

comparing fields in 2 different tables using SQL

I would like to compare if the address fields in contact table are different to that of the delivery table.
SELECT contactID, addressline1
FROM contact
where contactID = '0018319'
Below is the delivery table which contains the old details.
SELECT contactID, addressline1
FROM delivery
where contactID = '0018319'
SELECT contactID, d.addressline1, c.addressline1
FROM delivery d
INNER JOIN contact c on d.contactID = c.contactID
where d.addressline1 != c.addressline1
If you want to return a flag, then you would use case in the select statement:
select contactId,
(case when d.addressline1 = c.addressline1 or d.addressline1 is null and c.addressline1 is null
then 'SAME'
else 'DIFFERENT'
end) as SameOrDifferent
from contact c join
delivery d
on c.contactId = d.contactId
where contactId = '0018319';
This is going to compare each address in the two tables.
If you want to know if all are the same, then the query is more complicated. The idea is to do a full outer join between the two table (for the given contractid) on addressline1. If all the addresslines match, then the full outer join will never produce NULL values. If any are missing (on either side), then there will be NULL values.
select coalesce(c.contactId, d.contactId) as contactId,
(case when sum(case when c.addressline1 is null or d.addressline1 is null
then 1
else 0
end) = 0
then 'SAME'
else 'DIFFERENT'
end) as SameOrDifferent
from (select c.* from contact c where c.contactId = '0018319') c full outer join
(select d.* from delivery d where d.contactId = '0018319') d
on c.addressline1 = d.addressline1 and
c.contactId = d.contactId -- not actually necessary but useful for multiple contacts
group by coalesce(c.contactId, d.contactId)