I have spent a full day on this and just don't get it. Usually I am pretty good with this stuff but I am just getting back in to SQL and just cannot figure this out. Any help you can provide would be very much appreciated.
I am running SQL Server 2008 R2. I have a database where I keep patient data (no names, just identifiers) and clinical test results. I have put together a view to query the various data tables and collect the information I need into one spot. The results of my query give me a table like this: (Tests and values are made up - I know nothing about the tests. I'm just the tech - lol.)
PtName | Age | Race | Ethnicity | DrawDate | TestType | TestResult
PT001 | 17 | White | Non-Hispanic | 05/17/2011 | WBC | 6.8
PT001 | 17 | White | Non-Hispanic | 05/17/2011 | HGB | 14.1
PT001 | 17 | White | Non-Hispanic | 05/17/2011 | Platelets | 142.0
PT001 | 17 | White | Non-Hispanic | 05/29/2011 | WBC | 7.2
PT002 | 34 | White | Hispanic | 05/17/2011 | WBC | 7.8
PT002 | 34 | White | Hispanic | 05/17/2011 | Platelets | 255.0
What I want is:
PtName | Age | Race | Ethnicity | DrawDate | WBC | HGB | Platelets
PT001 | 17 | White | Non-Hispanic | 05/17/2011 | 6.8 | 14.1 | 142.0
PT001 | 17 | White | Non-Hispanic | 05/29/2011 | 7.2 | |
PT002 | 34 | White | Hispanic | 05/17/2011 | | | 255.0
I worked out a PIVOT query (first one - very proud, didn't work - not so proud) but then realized that using the aggregate in the PIVOT query would not give me multiple visits for each patient.
I am dealing with hundreds of patients, some have multiple visits, with up to eight tests each. Is a PIVOT query the best way to deal with this? Is there a better way? Some form of subquery perhaps? I am willing to try about anything.