How can I select the entire row when using max - sql

I have a table with the following columns:
SignatureID
PatientID
PatientVisitID
TreatAuthDate
HIPAADate
DrugTestDate
Now I have the following Select statement:
SELECT *
FROM tblSignature
WHERE PatientID = 12345
This select statement returns 8 rows. What I need to accomplish is getting the MAX TreatAuthDate - and with that MAX TreatAuthDate I need the PatientVisitID. Then I need the same type of information for the HipaaDate and DrugTestDate. How can I do this?

SELECT TOP 1 *
FROM tblSignature
WHERE PatientID = 12345
ORDER BY
TreatAuthDate DESC
To get three last results for different definitions of "last", use this:
SELECT *
FROM (
SELECT TOP 1 'LastThreatAuth' AS which, ts.*
FROM tblSignature ts
WHERE PatientID = 12345
ORDER BY
TreatAuthDate DESC
) SrcTreatAuth
UNION ALL
SELECT *
FROM (
SELECT TOP 1 'LastHIPAA' AS which, ts.*
FROM tblSignature ts
WHERE PatientID = 12345
ORDER BY
HIPAADate DESC
) SrcHIPAA
UNION ALL
SELECT *
FROM (
SELECT TOP 1 'LastDrugTest' AS which, ts.*
FROM tblSignature ts
WHERE PatientID = 12345
ORDER BY
DrugTestDate DESC
) SrcDrugTest

SELECT patientid, max(Treatauthdate), max (HippaDAte) , max (DrugTestDate)
FROM tblSignature
WHERE PatientID = 12345
group by patientid
Note you can't ask for signatureid in this case as you would not filter any records out (I'm making the assumption signatureid is your PK). Further to get the max of each date per patient, it is likely they are each on a differnt row of the table so would not have the same signatureid.
To get the visit date for each type might be more difficult as each may be a separate visit.
try something like
select a.patientid, Treatvisitdate, Treatauthdate,Hippavisitdate, HippaDate, DrugTestvisitdate,
DrugTestDate
(SELECT patientid, patientvisitdate as Treatvisitdate, max(Treatauthdate) as Treatauthdate
FROM tblSignature
WHERE PatientID = 12345
group by patientid,patientvisitdate)a
join
(SELECT patientid, patientvisitdate as Hippavisitdate, max(HippaDate) as HippaDate
FROM tblSignature
WHERE PatientID = 12345
group by patientid,patientvisitdate) b on a.patientid = b.patientid
join
(SELECT patientid, patientvisitdate as DrugTestvisitdate, max(DrugTestDate) as DrugTestDate
FROM tblSignature
WHERE PatientID = 12345
group by patientid,patientvisitdate) c on a.patientid = c.patientid
YOu might need left joins if some of the dates might not be in there.

Related

How to select the min and max date from a table into another table on the same row? in SQL

So I have an example of a table like below:
ID
Category
AdmissionDate
DischargeDate
A1
A
2017-07-20
2017-07-21
A1
B
2017-07-27
2017-07-28
I would like to select the Min and Max date and also create two new columns based on the min and max date as below:
ID
MinAdmissionDate
MaxDischargeDate
AdmittedCategory
DischargeCategory
A1
2017-07-20
2017-07-28
A
B
The admitted category would be based on the MinAdmissionDate while the dischargeCategory would be based on the MaxDischargeDate
You could try joining to grouped table:
select
grouped.ID,
grouped.AdmissionDate,
grouped.DischargeDate,
admission.Category admissionCategory,
discharge.Category dischargeCategory
from
(
select
ID,
min(AdmissionDate) AdmissionDate,
max(DischargeDate) DischargeDate
from testTable
group by ID
) [grouped]
left join testTable [admission] on
[grouped].ID = [admission].ID and
[grouped].AdmissionDate = [admission].AdmissionDate
left join testTable [discharge] on
[grouped].ID = [discharge].ID and
[grouped].DischargeDate = [discharge].DischargeDate
Database fiddle.
Try something like this:
WITH cte As
(
SELECT
ID,
Category,
AdmissionDate,
DischargeDate,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY AdmissionDate) As ARN,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DischargeDate DESC) As DRN
FROM
YourTable
)
SELECT
A.ID,
A.AdmissionDate As MinAdmissionDate,
D.DischargeDate As MaxDischargeDate,
A.Category As AdmittedCategory,
D.Category As DischargeCategory
FROM
cte As A
INNER JOIN cte As D
ON D.ID = A.ID
And A.ARN = 1
And D.DRN = 1
;
Demo
ROW_NUMBER

Group by column and get max and min id on sql

I got a table with theses Column :
ID_REAL,DATE_REAL,NAME_REAL
I want to make a query to get result like this with a group by on the name
NAME | MAX(DATE_REAL) | ID_REAL of the MAX(DATE_REAL) | MIN(DATE_REAL) | ID_REAL of the MIN(DATE_REAL)
I dont know how to make it for the moment I have
select NAME_REAL,max(DATE_REAL),ID_REAL from MYREALTABLE group by NAME_REAL,ID_REAL
select NAME_REAL,min(DATE_REAL),ID_REAL from MYREALTABLE group by NAME_REAL,ID_REAL
But is not whats I need, and also I need only 1 query
Thanks you
I think the following should work by finding the records which have the minimum and maximum dates per name and joining those two queries.
select
mn.NAME_REAL,
MIN_DATE_REAL,
ID_REAL_OF_MIN_DATE_REAL,
MAX_DATE_REAL,
ID_REAL_OF_MAXDATE_REAL
from
(
select NAME_REAL,
DATE_REAL as MIN_DATE_REAL,
ID_REAL as ID_REAL_OF_MIN_DATE_REAL,
from (
select
NAME_REAL,
ID_REAL,
DATE_REAL,
row_number() over (partition by NAME_REAL order by DATE_REAL asc) as date_order_asc
from MYREALTABLE
)
where date_order_asc = 1
) mn
inner join
(
select NAME_REAL,
DATE_REAL as MAX_DATE_REAL,
ID_REAL as ID_REAL_OF_MAX_DATE_REAL,
from (
select
NAME_REAL,
ID_REAL,
DATE_REAL,
row_number() over (partition by NAME_REAL order by DATE_REAL desc) as date_order_desc
from MYREALTABLE
)
where date_order_desc = 1
) mx
on mn.NAME_REAL = mx.NAME_REAL
You can join the two results into a single query result as follows
select o.NAME_REAL,o.max,o.id_real,t.min,o.id_real from (
select NAME_REAL,max(DATE_REAL) as max,ID_REAL, from MYREALTABLE group by NAME_REAL,ID_REAL)
as o inner join
(select NAME_REAL,min(DATE_REAL),ID_REAL from MYREALTABLE group by NAME_REAL,ID_REAL
) as t on o.NAME_REAL=t.NAME_REAL
Try the below -
select NAME_REAL,ID_REAL,max(DATE_REAL) as max_date, min(DATE_REAL) as min_date
from MYREALTABLE
group by NAME_REAL,ID_REAL

Select every second record then determine earliest date

I have table that looks like the following
I have to select every second record per PatientID that would give the following result (my last query returns this result)
I then have to select the record with the oldest date which would be the following (this is the end result I want)
What I have done so far: I have a CTE that gets all the data I need
WITH cte
AS
(
SELECT visit.PatientTreatmentVisitID, mat.PatientMatchID,pat.PatientID,visit.RegimenDate AS VisitDate,
ROW_NUMBER() OVER(PARTITION BY mat.PatientMatchID, pat.PatientID ORDER BY visit.VisitDate ASC) AS RowNumber
FROM tblPatient pat INNER JOIN tblPatientMatch mat ON mat.PatientID = pat.PatientID
LEFT JOIN tblPatientTreatmentVisit visit ON visit.PatientID = pat.PatientID
)
I then write a query against the CTE but so far I can only return the second row for each patientID
SELECT *
FROM
(
SELECT PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate, RowNumber FROM cte
) as X
WHERE RowNumber = 2
How do I return the record with the oldest date only? Is there perhaps a MIN() function that I could be including somewhere?
If I follow you correctly, you can just order your existing resultset and retain the top row only.
In standard SQL, you would write this using a FETCH clause:
SELECT *
FROM (
SELECT
visit.PatientTreatmentVisitID,
mat.PatientMatchID,
pat.PatientID,
visit.RegimenDate AS VisitDate,
ROW_NUMBER() OVER(PARTITION BY mat.PatientMatchID, pat.PatientID ORDER BY visit.VisitDate ASC) AS rn
FROM tblPatient pat
INNER JOIN tblPatientMatch mat ON mat.PatientID = pat.PatientID
LEFT JOIN tblPatientTreatmentVisit visit ON visit.PatientID = pat.PatientID
) t
WHERE rn = 2
ORDER BY VisitDate
OFFSET 0 ROWS FETCH FIRST 1 ROW ONLY
This syntax is supported in Postgres, Oracle, SQL Server (and possibly other databases).
If you need to get oldest date from all selected dates (every second row for each patient ID) then you can try window function Min:
SELECT * FROM
(
SELECT *, MIN(VisitDate) OVER (Order By VisitDate) MinDate
FROM
(
SELECT PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate,
RowNumber FROM cte
) as X
WHERE RowNumber = 2
) Y
WHERE VisitDate=MinDate
Or you can use SELECT TOP statement. The SELECT TOP clause allows you to limit the number of rows returned in a query result set:
SELECT TOP 1 PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate FROM
(
SELECT *
FROM
(
SELECT PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate,
RowNumber FROM cte
) as X
WHERE RowNumber = 2
) Y
ORDER BY VisitDate
For simplicity add order desc on date column and use TOP to get the first row only
SELECT TOP 1 *
FROM
(
SELECT PatientTreatmentVisitID,PatientMatchID,PatientID, VisitDate, RowNumber FROM cte
) as X
WHERE RowNumber = 2
order by VisitDate desc

Sql select distinct row by a columns highest value

I am having an issue trying to select one row per city name. This is the following collection I am getting:
This is my query so far:
select pl.PlaceId,
pl.Name,
pop.NumberOfPeople,
pop.Year
from dbo.Places pl
inner join dbo.Populations pop
on pop.PlaceId = pl.PlaceId
where pop.NumberOfPeople >= 1000
and pop.NumberOfPeople <= 99999
I am trying to get it to where it only selects a city one time, but uses the most recent date. So in the above picture, I would only see Abbeville for 2016 and not 2015. I believe I need to do either a group by or do a sub query to flatten the results. If anybody has any advice on how I can handle this, it will be greatly appreciated.
Assuming you are using SQLSERVER,you can use Rownumber
;with cte
as
(select pl.PlaceId,
pl.Name,
pop.NumberOfPeople,
pop.Year,
row_number() over(partition by pl.Name order by year desc) as rownum
from dbo.Places pl
inner join dbo.Populations pop
on pop.PlaceId = pl.PlaceId
where pop.NumberOfPeople >= 1000
and pop.NumberOfPeople <= 99999
)
select * from cte where rownum=1
The following query serves the purpose.
CREATE TABLE #TEMP_TEST
(
PlaceId INT,
Name VARCHAR(50),
NumberOfPeople INT,
YEAR INT
)
INSERT INTO #TEMP_TEST
SELECT 1,'Abbeville',2603,2016
UNION
SELECT 5,'Alabester',32948,2016
UNION
SELECT 9,'Aubum',63118,2016
UNION
SELECT 1,'Abbeville',2402,2015
UNION
SELECT 5,'Alabester',67902,2017
SELECT PlaceId, Name, NumberOfPeople, YEAR FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY PlaceId ORDER BY YEAR DESC) RNO,
PlaceId, Name, NumberOfPeople, YEAR
FROM #TEMP_TEST
)T
WHERE RNO = 1
DROP TABLE #TEMP_TEST

Join two queries from the same table - SELECT DISTINCT?

I have two tables linked by an AUTO_KEY field, from one table I'm retrieving the number (id), from the other I get several statuses by number(id), each status has a date associated to it.
I need to restrict the results only to the maximum/latest date for all numbers(ids) and the corresponding status
SELECT
OPERATION.NUMBER,
STATUS.STATUS,
Max(STATUS.DATE)
FROM
STATUS,
OPERATION
WHERE
OPERATION.AUTO_KEY = STATUS.AUTO_KEY
From here
Number Status Date
-----------------------------
1 A 10/20/13
1 B 10/15/13
2 A 10/10/13
2 AX 10/05/13
2 AD 10/03/13
3 DD 10/03/13
The outcome should be
Number Status Date
-----------------------------
1 A 10/20/13
2 A 10/10/13
3 DD 10/03/13
Thanks in advance
You can use a CTE with ROW_NUMBER() function. Also Please use a Table JOIN instead FROM STATUS, OPERATION
;With CTE AS (
SELECT O.NUMBER, S.STATUS, S.DATE,
ROW_NUMBER() OVER (ORDER BY S.DATE DESC) RN
FROM STATUS S JOIN OPERATION O
ON O.AUTO_KEY = S.AUTO_KEY
)
SELECT NUMBER, STATUS, DATE
FROM CTE
WHERE RN = 1
ORDER BY NUMBER
SELECT OPERATION.CNUMBER,
STATUS.STATUS,
STATUS.CDATE
FROM STATUS,
OPERATION
WHERE OPERATION.AUTO_KEY = STATUS.AUTO_KEY
AND STATUS.CDATE = (
SELECT MAX(STATUS.CDATE) MAX_DATE
FROM STATUS,
OPERATION
WHERE OPERATION.AUTO_KEY = STATUS.AUTO_KEY
GROUP BY OPERATION.CNUMBER )