Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Query help - possibly RANK() over partition and Pivot (maybe not)

$
0
0

This is just a sample and is not the actual table and data. The table cannot be changed.

I need to select all patients whose latest CareType = ‘Attending’ where the DrID = 1372 (Daffy Duck). The latest is determined by the VisitDate. The DrID, Doctor, PatientID, and CareType are the columns selected. I also need to select the DrID as PrimaryID and Doctor as PrimaryDoctor for the latest CareType = ‘Primary Service Coordinator’ when it exists.

Table name – Mess

PK – MessID

Sample data:

MessID

DrID

Doctor

PatientID

CareType

VisitDate

5822

1673

Sylvester

400

Care Provider

12/15/2013

6082

1146

Tweety Bird

400

Primary Service Coordinator

12/14/2013

7108

1597

Bugs Bunny

400

Residential Provider

12/1/2013

8095

1372

Daffy Duck

400

Attending

11/25/2013

9290

1456

Yosemite Sam

400

Care Provider

11/10/2013

1

1086

Elmer Fudd

500

Licensed Professional

12/15/2013

567

1557

Porky Pig

500

Primary Service Coordinator

12/10/2013

595

1607

Foghorn Leghorn

500

Case Manager

12/9/2013

4911

1012

Wile E Coyote

500

Licensed Professional

12/5/2013

7453

1148

Roadrunner

500

Primary Service Coordinator

12/5/2013

10587

1372

Daffy Duck,

500

Attending

11/20/2013

10918

1048

Speedy Gonzales

500

Nurse

11/15/2013

12360

1744

Young, Robert

500

Attending

11/12/2013

10587

1372

Daffy Duck,

600

Attending

11/20/2013

17417

1597

Bugs Bunny

600

Attending

11/10/2013

17628

1456

Yosemite Sam

600

Care Provider

11/4/2013

Results:

DrID

Doctor

PatientID

CareType

PrimaryID

PrimaryDoctor

1372

Daffy Duck

400

Attending

1146

Tweety Bird

1372

Daffy Duck,

500

Attending

1557

Porky Pig

1372

Daffy Duck,

600

Attending

 

 

The following will get the results for patients whose latest ‘Attending’ is DrID = 1372.

Select * from
(Select M.DrID, M.Doctor, M.PatientID, M.CareType
RANK() over (partition by M.PatientID order by M.VisitDate desc) as latest
from Mess  M
Where M.DrID = ‘1372’
And M.CareType = ‘Attending’) text
Where latest = 1

I have some ideas on how to build on that query but would like to see what others suggest. Feel free to fix or completely scrap the above query.

Thanks



Additional info: There will be patients in the table that will not have DrID = '1372' with CareType = 'Attending'. I should have included an entry for those cases in my sample. Those patients will not be part of the results.

Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>