SQL Multiple inner joins with max() for latest recorded entry - sql

Attempting to build SQL with INNER JOIN's. The INNER JOIN's work ok, now I need to add the MAX() function for limiting the rows to just most recent. Added this INNER JOIN client_diagnosis_record ON SELECT cr.PATID, cr.date_of_diagnosis, cr.most_recent_diagnosis...
Received this SQL code error, need some help, I'm sure it a simple oversight but my eyes are getting dim from looking so long...
Syntax error: [SQLCODE: <-4>:
SQLCODE: <-4>:<A term expected, beginning with one of the following: identifier, constant, aggregate, %ALPHAUP, %EXACT, %MVR, %SQLSTRING, %
[%msg: < The SELECT list of the subquery
SELECT pd.patient_name,
cr.PATID,
cr.date_of_diagnosis,
cr.EPISODE_NUMBER,
ce.diagnosing_clinician_value,
ce.data_entry_user_name,
most_recent_diagnosis
FROM client_diagnosis_record cr
INNER JOIN patient_current_demographics pd ON cr.patid = pd.patid
INNER JOIN client_diagnosis_entry ce ON ce.patid = pd.patid
AND cr.ID = ce.DiagnosisRecord
INNER JOIN client_diagnosis_record ON (SELECT cr.PATID,
cr.date_of_diagnosis,
cr.most_recent_diagnosis
FROM ( SELECT patid,
date_of_diagnosis,
MAX(ID) AS most_recent_diagnosis
FROM client_diagnosis_record) cr
INNER JOIN RADplus_users ru ON ru.staff_member_id = ce.diagnosing_clinician_code
WHERE cr.PATID <> '1'
AND ce.diagnosis_status_value ='Active'
AND (ru.user_description LIKE '%SOA' OR ru.user_description LIKE '%OA')
GROUP BY cr.PATID

I tried to re-format you query and it seems your query syntax is not correct. You may try below query -
SELECT pd.patient_name,
cr.PATID,
cr.date_of_diagnosis,
cr.EPISODE_NUMBER,
ce.diagnosing_clinician_value,
ce.data_entry_user_name,
most_recent_diagnosis
FROM client_diagnosis_record cr
INNER JOIN (SELECT patid,
date_of_diagnosis,
MAX(ID) AS most_recent_diagnosis
FROM client_diagnosis_record
GROUP BY patid,
date_of_diagnosis) cr2 ON cr.PATID = cr2.PATID
AND cr.date_of_diagnosis = cr2.date_of_diagnosis
AND cr.ID = cr2.most_recent_diagnosis
INNER JOIN patient_current_demographics pd ON cr.patid = pd.patid
INNER JOIN client_diagnosis_entry ce ON ce.patid = pd.patid
AND cr.ID = ce.DiagnosisRecord
INNER JOIN RADplus_users ru ON ru.staff_member_id = ce.diagnosing_clinician_code
WHERE cr.PATID <> '1'
AND ce.diagnosis_status_value ='Active'
AND (ru.user_description LIKE '%SOA' OR ru.user_description LIKE '%OA')
GROUP BY cr.PATID

Related

Access Query - Group by and Max

I have been working on this for a few hours now and just can not figure it out.
How would I go about sorting this query by enco_id and only having the max of each clpr_id show up. for example:
Here is my MSAccess Sql Code
SELECT dbo_Client.med_rec_no, dbo_Encounter.episode_number, dbo_client_program.enco_id, dbo_client_program.clpr_id, dbo_client_program.prle_id, dbo_PROGRAM_LEVEL.prle_name, dbo_Client.fname, dbo_Client.lname, dbo_DISCHARGE_STATUS.dist_name, DS2.dist_name
FROM (((((dbo_Client INNER JOIN dbo_Encounter ON dbo_Client.client_id = dbo_Encounter.client_id) INNER JOIN dbo_Episode_info ON dbo_Encounter.enco_id = dbo_Episode_info.enco_id) INNER JOIN dbo_DISCHARGE_STATUS ON dbo_Episode_info.dist_id = dbo_DISCHARGE_STATUS.dist_id) INNER JOIN dbo_client_program ON dbo_Encounter.enco_id = dbo_client_program.enco_id) INNER JOIN dbo_DISCHARGE_STATUS AS DS2 ON dbo_client_program.dist_id = DS2.dist_id) INNER JOIN dbo_PROGRAM_LEVEL ON dbo_client_program.prle_id = dbo_PROGRAM_LEVEL.prle_id;
Also here is what my query looks like
EDIT:
This is the code I am trying to use now and it still is not working
SELECT dbo_Client.client_id, dbo_Client.med_rec_no, dbo_Encounter.episode_number, dbo_Encounter.start_date, dbo_Encounter.end_date, dbo_client_program.clpr_id, dbo_client_program.enco_id, dbo_PROGRAM_LEVEL.prle_name, dbo_Client.fname, dbo_Client.lname, dbo_DISCHARGE_STATUS.dist_name, DS2.dist_name
FROM (((((dbo_Client INNER JOIN dbo_Encounter ON dbo_Client.client_id = dbo_Encounter.client_id) INNER JOIN dbo_Episode_info ON dbo_Encounter.enco_id = dbo_Episode_info.enco_id) INNER JOIN dbo_DISCHARGE_STATUS ON dbo_Episode_info.dist_id = dbo_DISCHARGE_STATUS.dist_id) INNER JOIN dbo_client_program ON dbo_Encounter.enco_id = dbo_client_program.enco_id) INNER JOIN dbo_DISCHARGE_STATUS AS DS2 ON dbo_client_program.dist_id = DS2.dist_id) INNER JOIN dbo_PROGRAM_LEVEL ON dbo_client_program.prle_id = dbo_PROGRAM_LEVEL.prle_id
WHERE dbo_client_program.clpr_id IN
(SELECT TOP 1 clpr_id FROM dbo_client_program as New
WHERE New.clpr_id = dbo_client_program.clpr_id
ORDER by dbo_client_program.clpr_id DESC) AND (dbo_DISCHARGE_STATUS.dist_name <> DS2.dist_name) AND dbo_Encounter.start_date > #1/1/2020# AND dbo_Encounter.end_date > #1/1/2020#
ORDER BY dbo_Encounter.episode_number;
As you are still understanding the aggregate queries my suggestion is:
1-Create a query where you group by all fields and max(clpr_id). Save this as "Query1"
2-Create another query based on "Query1" and sort by "enco_id "

Looking to add in a Count query with Group by INTO an existing working query

Goal:
I wish to get the Count of how many times a WorkItem was re-assigned
From what I understand the proper query is the following:
SELECT
WorkItemDimvw.Id,
COUNT(WorkItemAssignedToUserFactvw.WorkItemAssignedToUser_UserDimKey) AS Assignments
FROM WorkItemDimvw INNER JOIN WorkItemAssignedToUserFactvw
ON WorkItemDimvw.WorkItemDimKey = WorkItemAssignedToUserFactvw.WorkItemDimKey
GROUP BY WorkItemDimvw.Id
The EXISTING query is below and I'm wondering / forgeting if I should:
Just add in COUNT(WorkItemAssignedToUserFactvw.WorkItemAssignedToUser_UserDimKey) AS Assignments since joins are existing, except it is group by WorkItemDimvw.Id
Should it instead be a subquery in the Select below?
Query:
SELECT
SRD.ID,
SRD.Title,
SRD.Description,
SRD.EntityDimKey,
WI.WorkItemDimKey,
IATUFact.DateKey
FROM
SLAConfigurationDimvw
INNER JOIN SLAInstanceInformationFactvw
ON SLAConfigurationDimvw.SLAConfigurationDimKey = SLAInstanceInformationFactvw.SLAConfigurationDimKey
RIGHT OUTER JOIN ServiceRequestDimvw AS SRD
INNER JOIN WorkItemDimvw AS WI
ON SRD.EntityDimKey = WI.EntityDimKey
LEFT OUTER JOIN WorkItemAssignedToUserFactvw AS IATUFact
ON WI.WorkItemDimKey = IATUFact.WorkItemDimKey
AND IATUFact.DeletedDate IS NULL
The trick is to aggregate the data on a sub query, before you join it.
SELECT
SRD.ID,
SRD.Title,
SRD.Description,
SRD.EntityDimKey,
WI.WorkItemDimKey,
IATUFact.DateKey,
IATUFact.Assignments
FROM
SLAConfigurationDimvw
INNER JOIN
SLAInstanceInformationFactvw
ON SLAConfigurationDimvw.SLAConfigurationDimKey = SLAInstanceInformationFactvw.SLAConfigurationDimKey
RIGHT OUTER JOIN
ServiceRequestDimvw AS SRD
ON <you're missing something here>
INNER JOIN
WorkItemDimvw AS WI
ON SRD.EntityDimKey = WI.EntityDimKey
LEFT OUTER JOIN
(
SELECT
WorkItemDimKey,
DateKey,
COUNT(WorkItemAssignedToUser_UserDimKey) AS Assignments
FROM
WorkItemAssignedToUserFactvw
WHERE
DeletedDate IS NULL
GROUP BY
WorkItemDimKey,
DateKey
)
IATUFact
ON WI.WorkItemDimKey = IATUFact.WorkItemDimKey

select top 1 in subquery?

I'm trying to get a top 1 returned for each code in this query but this is giving me syntax errors. Any ideas what I can do?
SELECT d.doc_no,
d.doc_short_name,
d.doc_name,
r.revision_code,
r.revision,
r.description,
dtg.group_name,
(SELECT top 1 di.index_user_id
FROM document_instance
WHERE doc_no = d.doc_no
ORDER BY entry_time DESC) AS 'last indexed by'
FROM documents d
LEFT JOIN document_revision r ON r.doc_no = d.doc_no
LEFT JOIN document_instance di ON di.doc_no = d.doc_no
LEFT JOIN document_type_group dtg ON dtg.doc_no = d.doc_no
Assuming Sybase ASE, the top # clause is only supported in derived tables, ie, it's not supported in correlated sub-queries like you're attempting.
Also note that order by is not supported in any sub-queries (derived table or correlated).
If I'm reading the query correctly, you want the index_user_id for the record with the max(entry_time); if this is correct, and assuming a single record is returned for a given doc_no/entry_time combo, you could try something like:
SELECT d.doc_no,
d.doc_short_name,
d.doc_name,
r.revision_code,
r.revision,
r.description,
dtg.group_name,
(SELECT d2.index_user_id
FROM document_instance d2
WHERE d2.doc_no = d1.doc_no
and d2.entry_time = (select max(d3.entry_time)
from document_instance d3
where d3.doc_no = d1.doc_no)
) as 'last indexed by'
FROM documents d
LEFT JOIN document_revision r ON r.doc_no = d.doc_no
LEFT JOIN document_instance d1 ON d1.doc_no = d.doc_no
LEFT JOIN document_type_group dtg ON dtg.doc_no = d.doc_no

Power Query SQL code issue

I'm trying to run this SQL code in Power Query but keep getting the following error Message:
Incorrect syntax near the keyword 'GROUP'
The SQL code I'm using is
SELECT Groups.GroupName, AgentTeams.TeamName, Agent.Firstname, Agent.Lastname, CRC.Description, Count(History.HistoryID) AS CountOfHistoryID
FROM ((GroupAgent
INNER JOIN Groups ON GroupAgent.GroupID = Groups.GroupID)
INNER JOIN ((Agent LEFT JOIN History ON Agent.AgentID = History.AgentID)
LEFT JOIN CRC ON History.CRC = CRC.CRC) ON GroupAgent.AgentID = Agent.AgentID)
INNER JOIN (AgentTeams
INNER JOIN AgentStartDates ON AgentTeams.TeamID = AgentStartDates.TeamID) ON GroupAgent.AgentID = AgentStartDates.AgentID
WHERE (((History.CallDateTime) Between GetDate() And DateAdd(d,1,GetDate())
GROUP BY Groups.GroupName, AgentTeams.TeamName, Agent.Firstname, Agent.Lastname, CRC.Description
ORDER BY Groups.GroupName, AgentTeams.TeamName;
Could someone help me fix this or advise me where I'm going wrong?
Adam
Close the parentheses....
SELECT Groups.GroupName, AgentTeams.TeamName, Agent.Firstname, Agent.Lastname, CRC.Description, Count(History.HistoryID) AS CountOfHistoryID
FROM ((GroupAgent INNER JOIN Groups ON GroupAgent.GroupID = Groups.GroupID) INNER JOIN ((Agent LEFT JOIN History ON Agent.AgentID = History.AgentID) LEFT JOIN CRC ON History.CRC = CRC.CRC) ON GroupAgent.AgentID = Agent.AgentID) INNER JOIN (AgentTeams INNER JOIN AgentStartDates ON AgentTeams.TeamID = AgentStartDates.TeamID) ON GroupAgent.AgentID = AgentStartDates.AgentID
WHERE (((History.CallDateTime) Between GetDate() And DateAdd(d,1,GetDate())))
GROUP BY Groups.GroupName, AgentTeams.TeamName, Agent.Firstname, Agent.Lastname, CRC.Description
ORDER BY Groups.GroupName, AgentTeams.TeamName;
Hope it helps...

Subquery with multiple joins involved

Still trying to get used to writing queries and I've ran into a problem.
Select count(region)
where (regionTable.A=1) in
(
select jxn.id, count(jxn.id) as counts, regionTable.A
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
group by jxn.id, regionTable.A
)
The inner query gives an ID number in one column, the amount of times they appear in the table, and then a bit attribute if they are in region A. The outer query works but the error I get is incorrect syntax near the keyword IN. Of the inner query, I would like a number of how many of them are in region A
You must specify table name in query before where
Select count(region)
from table
where (regionTable.A=1) in
And you must choose one of them.
where regionTable.A = 1
or
where regionTable.A in (..)
Your query has several syntax errors. Based on your comments, I think there is no need for a subquery and you want this:
select jxn.id, count(jxn.id) as counts, regionTable.A
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
where regionTable.A = 1
group by jxn.id, regionTable.A
which can be further simplified to:
select jxn.id, count(jxn.id) as counts
, 1 as A --- you can even omit this line
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
where regionTable.A = 1
group by jxn.id
You are getting the error because of this line:
where (regionTable.A=1)
You cannot specify a condition in a where in clause, it should only be column name
Something like this may be what you want:
SELECT COUNT(*)
FROM
(
select jxn.id, count(jxn.id) as counts, regionTable.A
from
jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
group by jxn.id, regionTable.A
) sq
WHERE sq.a = 1