I need to be able to create a multi-column PIVOT in order to show values for the same LabDate and LabID for 1 or more dates in a year. When a patient visits a lab on a specific date (LabDate) we record the values of all testing (LabID) as separate columns for the same LabID. So, for example we may want the following columns to display - PatientID, LabID and LabValue. If there are 2 or more LabDates in the same year then multiple LabValue columns will display. The user would like the LabDate to show at the top of the column, if possible. Below are the 2 tables and the SELECT I use to render all rows.
CREATE TABLE [dbo].[tblLabsPerPatient]( [PatientLabID] [int] IDENTITY(1,1) NOT NULL, [PatientID] [int] NULL, [LabDate] [smalldatetime] NULL, CONSTRAINT [PK_tblLabByPatient] PRIMARY KEY CLUSTERED ( [PatientLabID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] CREATE TABLE [dbo].[tblLabsPerPatientDetail]( [PatientLabID] [int] NOT NULL, [LabID] [int] NOT NULL, [LabValue] [real] NULL, CONSTRAINT [PK_tblLabByPatientDetail] PRIMARY KEY CLUSTERED ( [PatientLabID] ASC, [LabID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] SELECT dbo.tblLabsPerPatient.PatientID, dbo.tblLabsPerPatient.LabDate, dbo.tblLabsPerPatientDetail.PatientLabID, dbo.tblLabsPerPatientDetail.LabID, dbo.tblLabsPerPatientDetail.LabValue FROM dbo.tblLabsPerPatient INNER JOIN dbo.tblLabsPerPatientDetail ON dbo.tblLabsPerPatient.PatientLabID = dbo.tblLabsPerPatientDetail.PatientLabID WHERE (dbo.tblLabsPerPatient.PatientID = 1666) AND (YEAR(dbo.tblLabsPerPatient.LabDate) = 2008)