Query returns incorrect result - sql

MY input table is patient_ID, and Appt_Resource_ID (Doctor) ( the second table is just getting the patient name )
Patient_ID Appt_Resource_ID
88299 47
88299 1
88299 40
88299 40
88299 40
88299 40
I am running an sql that is meant to write an output row for the patient_id and the Doctor_ID that occurs the most, in this case sb 40. But it's outputting Doctor_ID 1. Other cases I checked are doing correctly.
This is the query:
select distinct A.Patient_id, P.Patient_name, b.Appt_resource_id
from [PM].[vwGenPatApptInfo] A
inner join
(
select top 100 percent patient_id, Appt_resource_id, count(Appt_resource_id) as DR_count,
row_number() over (partition by patient_id order by count(*) desc) as seqnum
from [PM].[vwGenPatApptInfo]
where Patient_ID is NOT NULL
group by patient_id,Appt_resource_id
order by patient_id, seqnum
) B on B.Patient_ID = A.Patient_ID
and B.seqnum = 1
inner join [PM].[vwGenPatInfo] P on A.Patient_id = P.Patient_id
where A.Appt_DateTime >= DATEADD(yyyy, -2, GETDATE()) and A.Appt_Cancelled_Date is NULL
But the results are this:
Patient_ID Appt_Resource_ID
88299 1

Try this.
SELECT TOP 1 *
FROM (
SELECT Patient_ID, Appt_Resource_ID, COUNT(*) AS theCount
FROM vwGenPatApptInfo
GROUP BY Patient_ID, Appt_Resource_ID
WHERE ApptDateTime >= DATEADD(yyyy, -2, GETDATE()) and Appt_Cancelled_Date is NULL
) b
JOIN vwGenPatInfo p ON p.Patient_ID = b.Patient_ID
ORDER BY theCount DESC

This is not really an answer, sorry.
Your subquery finds the doctor that occurs most often for a patient. (If you want the most often occurring patient/doctor pair instead, then remove the partition clause from ROW_NUMBER.)
But then you join vwGenPatApptInfo again (as A). Why? And your join is even incomplete, because you only join by Patient_ID and not by Appt_resource_id, too. You are thus combining every most occurring doctor with other doctor records for the patient in a certain date range. These you dismiss again with DISTINCT.
I don't see however how your query gets the wrong doctor. If it had been A.Appt_resource_id you selected, that would have been a reason, but b.Appt_resource_id should be the most often occurring doctor.
I hope my comments above help you, though. Maybe you can simplify your query somehow and maybe get thus even rid of the error.
Good luck!

It might be not the most ideal solution, but try this:
;WITH CTE1 as (
SELECT Patient_ID, Appt_Resource_ID
, COUNT(*) OVER (PARTITION BY Patient_ID, Appt_Resource_ID) as CNT
FROM [PM].[vwGenPatApptInfo]
), CTE2 as (
SELECT Patient_ID, Appt_Resource_ID, CNT, RANK() OVER
(PARTITION BY Patient_ID ORDER BY CNT DESC) AS Rank
FROM CTE1
), CTE3 as (
SELECT Patient_ID, Appt_Resource_ID, CNT, Rank
FROM CTE2
WHERE Rank = 1
GROUP BY Patient_ID, Appt_Resource_ID, CNT, Rank
)
select distinct A.Patient_id, P.Patient_name, b.Appt_resource_id, B.CNT
from [PM].[vwGenPatApptInfo] A
INNER JOIN CTE3 as B on B.Patient_ID = A.Patient_ID
inner join [PM].[vwGenPatInfo] P on A.Patient_id = P.Patient_id
where A.Appt_DateTime >= DATEADD(yyyy, -2, GETDATE()) and A.Appt_Cancelled_Date is NULL

Related

Select only observations with a date more recent than the 30/6/2021 (dd/mm/yyyy)

I have the following code:
Select Tbl.Fromdate, Tbl.Por, Tbl.Porname, Tbl.Bmref3
From(
Select
To_Char(P.Fromdate, 'dd-mm-yyyy') As Fromdate, P.Por, P.Porname, W.Bmref3,
, RANK() OVER (PARTITION BY P.Por ORDER BY P.fromdate DESC) AS rank
From Tmsdat.Climandatecomps W
Inner Join Tmsdat.Portfolios P On (W.Porik = P.Porik)
Where 1=1
) Tbl
Where 1=1
And Tbl.Rank = 1
;
However, I wish to select only the observations that have a Fromdate more recent than the June 30, 2021. I tried to add Tbl.Fromdate> '30-06-2021' to the WHERE clause, but I did not receive the desired results.
Do you have any suggestions?
Thank you in advance.
Best regards,
You would put the condition in the inner query:
Select To_Char(P.Fromdate, 'dd-mm-yyyy') As Fromdate, P.Por, P.Porname, W.Bmref3,
RANK() OVER (PARTITION BY P.Por ORDER BY P.fromdate DESC) AS rank
From Tmsdat.Climandatecomps W inner join
Tmsdat.Portfolios P
On (W.Porik = P.Porik)
Where p.FromDate > date '2021-06-30'

Incremental count of duplicates

The following query displays duplicates in a table with the qty alias showing the total count, eg if there are five duplicates then all five will have the same qty = 5.
select s.*, t.*
from [Migrate].[dbo].[Table1] s
join (
select [date] as d1, [product] as h1, count(*) as qty
from [Migrate].[dbo].[Table1]
group by [date], [product]
having count(*) > 1
) t on s.[date] = t.[d1] and s.[product] = t.[h1]
ORDER BY s.[product], s.[date], s.[id]
Is it possible to amend the count(*) as qty to show an incremental count so that five duplicates would display 1,2,3,4,5?
The answer to your question is row_number(). How you use it is rather unclear, because you provide no guidance, such as sample data or desired results. Hence this answer is rather general:
select s.*, t.*,
row_number() over (partition by s.product order by s.date) as seqnum
from [Migrate].[dbo].[Table1] s join
(select [date] as d1, [product] as h1, count(*) as qty
from [Migrate].[dbo].[Table1]
group by [date], [product]
having count(*) > 1
) t
on s.[date] = t.[d1] and s.[product] = t.[h1]
order by s.[product], s.[date], s.[id];
The speculation is that the duplicates are by product. This enumerates them by date. Some combination of the partition by and group by is almost certainly what you need.

Displaying records that have more than 5 days inbetween them

I have 2 tables,
tblCustomer
CustomerID(PK), FirstName, Surname)
tblPurchases
PurchaseID(PK), PurchaseDate, Qty, CustomerID(FK).
I want to display all the customers who purchased products after five (5) days or more since their last purchase in the following manner.
FirstName diff in days since last purchase
Alex 7
Thanks!
Try with the below query.
SELECT FirstName, DATEDIFF(DAY, t.PurchaseDate, getdate()) as 'diff in days since last purchase'
FROM tblCustomer c
JOIN (SELECT CustomerID, MAX(PurchaseDate)PurchaseDate
FROM tblPurchases
GROUP BY CustomerID )t ON c.CustomerID=t.CustomerID
WHERE DATEDIFF(DAY, PurchaseDate, getdate())>5
SELECT FirstName,
DATEDIFF(DAY, t.PurchaseDate, getdate()) 'diff in days since last purchase'
FROM tblCustomer c
JOIN (SELECT CustomerID, MAX(PurchaseDate)PurchaseDate
FROM tblPurchases
GROUP BY CustomerID )t ON c.CustomerID=t.CustomerID
WHERE DATEDIFF(DAY, t.PurchaseDate, getdate())>5
Give a row number based on the last purchase date for each CustomerId by joining both the tables.
Then find the difference in number of days between current date and PurchaseDate by using DATEDIFF.And also give the number of days difference in the WHERE clause.
Query
;WITH CTE AS(
SELECT [rn] = ROW_NUMBER() OVER(
PARTITION BY t.[CustomerID]
ORDER BY t.[PurchaseDate] DESC
), t.[CustomerID], t.[FirstName], t.[PurchaseDate]
FROM (
SELECT t1.[CustomerID], t1.[FirstName], t2.[PurchaseDate]
FROM [tblCustomer] t1
JOIN [tblPurchases] t2
ON t1.[CustomerID] = t2.[CustomerID]
)t
)
SELECT [FirstName],
DATEDIFF(DAY, [PurchaseDate], GETDATE()) AS [diff in days since last purchase]
FROM CTE
WHERE [rn] = 1
AND DATEDIFF(DAY, [PurchaseDate], GETDATE()) > 5;
;WITH T AS
(
SELECT
*,
DATEDIFF(DAY, [PurchaseDate], GETDATE()) AS DiffInDays
FROM #tblPurchases
WHERE DATEDIFF(DAY, [PurchaseDate], GETDATE()) > 5
)
SELECT
C.FirstName,
MAX(DiffInDays) AS DiffInDays
FROM T
LEFT JOIN #tblCustomer C ON T.CustomerId=C.CustomerId
GROUP BY C.FirstName

How do I get the value associated with a MIN or MAX

I'm in the middle of creating a query and have it where I need the other values, however I am pulling a MIN and MAX date for individual patient_id. I'm wondering how I would go about how I would pull a value associated with that MIN or MAX date as well? I'm looking for a value the column provider_id which will show which doctor they saw on that MIN or MAX date. Here is what I have so far:
WITH test AS (
SELECT patient_id,
clinic,
SUM(amount) AS production,
MIN(tran_date) AS first_visit,
MAX(tran_date) AS last_visit
FROM transactions
WHERE impacts='P'
GROUP BY patient_id, clinic)
SELECT w.patient_id,
w.clinic,
p.city,
p.state,
p.zipcode,
p.sex,
w.production,
w.first_visit,
w.last_visit
FROM test w
LEFT JOIN patient p
ON (w.patient_id=p.patient_id AND w.clinic=p.clinic)
I believe that this will get what you're looking for:
;WITH CTE_Transactions AS (
SELECT DISTINCT
patient_id,
clinic,
SUM(amount) OVER (PARTITION BY patient_id, clinic) AS production,
FIRST_VALUE(tran_date) OVER (PARTITION BY patient_id, clinic ORDER BY tran_date) AS first_visit,
FIRST_VALUE(provider_id) OVER (PARTITION BY patient_id, clinic ORDER BY tran_date) AS first_provider_id,
LAST_VALUE(tran_date) OVER (PARTITION BY patient_id, clinic ORDER BY tran_date) AS last_visit,
LAST_VALUE(provider_id) OVER (PARTITION BY patient_id, clinic ORDER BY tran_date) AS last_provider_id,
ROW_NUMBER() OVER (PARTITION BY patient_id, clinic ORDER BY tran_date) AS row_num
FROM Transactions
WHERE impacts='P'
)
SELECT
w.patient_id,
w.clinic,
p.city,
p.state,
p.zipcode,
p.sex,
w.production,
w.first_visit,
w.last_visit
FROM
CTE_Transactions W
LEFT JOIN Patient P ON
W.patient_id = P.patient_id AND
W.clinic = P.clinic
INNER JOIN Provider FIRST_PROV ON
FIRST_PROV.provider_id = W.first_provider_id
INNER JOIN Provider LAST_PROV ON
LAST_PROV.provider_id = W.last_provider_id
WHERE
W.row_num = 1
I assume you are referring to the CTE. You can use conditional aggregation along with window functions. For instance, to get the amount for the first visit:
WITH test AS (
SELECT patient_id, clinic,
SUM(amount) AS production,
MIN(tran_date) AS first_visit,
MAX(tran_date) AS last_visit,
SUM(CASE WHEN tran_date = min_tran_date THEN amount END) as first_amount
FROM (SELECT t.*,
MIN(trans_date) OVER (PARTITION BY patient_id, clinic) as min_tran_date
FROM transactions
WHERE impacts = 'P'
) t
GROUP BY patient_id, clinic
)

How to count open records, grouped by hour and day in SQL-server-2008-r2

I have hospital patient admission data in Microsoft SQL Server r2 that looks something like this:
PatientID, AdmitDate, DischargeDate
Jones. 1-jan-13 01:37. 1-jan-13 17:45
Smith 1-jan-13 02:12. 2-jan-13 02:14
Brooks. 4-jan-13 13:54. 5-jan-13 06:14
I would like count the number of patients in the hospital day by day and hour by hour (ie at
1-jan-13 00:00. 0
1-jan-13 01:00. 0
1-jan-13 02:00. 1
1-jan-13 03:00. 2
And I need to include the hours when there are no patients admitted in the result.
I can't create tables so making a reference table listing all the hours and days is out, though.
Any suggestions?
To solve this problem, you need a list of date-hours. The following gets this from the admit date cross joined to a table with 24 hours. The table of 24 hours is calculating from information_schema.columns -- a trick for getting small sequences of numbers in SQL Server.
The rest is just a join between this table and the hours. This version counts the patients at the hour, so someone admitted and discharged in the same hour, for instance is not counted. And in general someone is not counted until the next hour after they are admitted:
with dh as (
select DATEADD(hour, seqnum - 1, thedatehour ) as DateHour
from (select distinct cast(cast(AdmitDate as DATE) as datetime) as thedatehour
from Admission a
) a cross join
(select ROW_NUMBER() over (order by (select NULL)) as seqnum
from INFORMATION_SCHEMA.COLUMNS
) hours
where hours <= 24
)
select dh.DateHour, COUNT(*) as NumPatients
from dh join
Admissions a
on dh.DateHour between a.AdmitDate and a.DischargeDate
group by dh.DateHour
order by 1
This also assumes that there are admissions on every day. That seems like a reasonable assumption. If not, a calendar table would be a big help.
Here is one (ugly) way:
;WITH DayHours AS
(
SELECT 0 DayHour
UNION ALL
SELECT DayHour+1
FROM DayHours
WHERE DayHour+1 <= 23
)
SELECT B.AdmitDate, A.DayHour, COUNT(DISTINCT PatientID) Patients
FROM DayHours A
CROSS JOIN (SELECT DISTINCT CONVERT(DATE,AdmitDate) AdmitDate
FROM YourTable) B
LEFT JOIN YourTable C
ON B.AdmitDate = CONVERT(DATE,C.AdmitDate)
AND A.DayHour = DATEPART(HOUR,C.AdmitDate)
GROUP BY B.AdmitDate, A.DayHour
This is a bit messy and includes a temp table with the test data you provided but
CREATE TABLE #HospitalPatientData (PatientId NVARCHAR(MAX), AdmitDate DATETIME, DischargeDate DATETIME)
INSERT INTO #HospitalPatientData
SELECT 'Jones.', '1-jan-13 01:37:00.000', '1-jan-13 17:45:00.000' UNION
SELECT 'Smith', '1-jan-13 02:12:00.000', '2-jan-13 02:14:00.000' UNION
SELECT 'Brooks.', '4-jan-13 13:54:00.000', '5-jan-13 06:14:00.000'
;WITH DayHours AS
(
SELECT 0 DayHour
UNION ALL
SELECT DayHour+1
FROM DayHours
WHERE DayHour+1 <= 23
),
HospitalPatientData AS
(
SELECT CONVERT(nvarchar(max),AdmitDate,103) as AdmitDate ,DATEPART(hour,(AdmitDate)) as AdmitHour, COUNT(PatientID) as CountOfPatients
FROM #HospitalPatientData
GROUP BY CONVERT(nvarchar(max),AdmitDate,103), DATEPART(hour,(AdmitDate))
),
Results AS
(
SELECT MAX(h.AdmitDate) as Date, d.DayHour
FROM HospitalPatientData h
INNER JOIN DayHours d ON d.DayHour=d.DayHour
GROUP BY AdmitDate, CountOfPatients, DayHour
)
SELECT r.*, COUNT(h.PatientId) as CountOfPatients
FROM Results r
LEFT JOIN #HospitalPatientData h ON CONVERT(nvarchar(max),AdmitDate,103)=r.Date AND DATEPART(HOUR,h.AdmitDate)=r.DayHour
GROUP BY r.Date, r.DayHour
ORDER BY r.Date, r.DayHour
DROP TABLE #HospitalPatientData
This may get you started:
BEGIN TRAN
DECLARE #pt TABLE
(
PatientID VARCHAR(10)
, AdmitDate DATETIME
, DischargeDate DATETIME
)
INSERT INTO #pt
( PatientID, AdmitDate, DischargeDate )
VALUES ( 'Jones', '1-jan-13 01:37', '1-jan-13 17:45' ),
( 'Smith', '1-jan-13 02:12', '2-jan-13 02:14' )
, ( 'Brooks', '4-jan-13 13:54', '5-jan-13 06:14' )
DECLARE #StartDate DATETIME = '20130101'
, #FutureDays INT = 7
;
WITH dy
AS ( SELECT TOP (#FutureDays)
ROW_NUMBER() OVER ( ORDER BY name ) dy
FROM sys.columns c
) ,
hr
AS ( SELECT TOP 24
ROW_NUMBER() OVER ( ORDER BY name ) hr
FROM sys.columns c
)
SELECT refDate, COUNT(p.PatientID) AS PtCount
FROM ( SELECT DATEADD(HOUR, hr.hr - 1,
DATEADD(DAY, dy.dy - 1, #StartDate)) AS refDate
FROM dy
CROSS JOIN hr
) ref
LEFT JOIN #pt p ON ref.refDate BETWEEN p.AdmitDate AND p.DischargeDate
GROUP BY refDate
ORDER BY refDate
ROLLBACK