I am trying to change my static PIVOT to a dynamic 2 column PIVOT as the report now needs to span over varying periods of time up to one year.
My data initially looks like this for 3 months.
[tt]
AbxDate Antibiotic DDD DOT
1/1/2015 AMPICILLIN 82.0 24.5
1/1/2015 CLINDAMYCIN 9.3 9.0
1/1/2015 VANCOMYCIN 74.8 94.7
2/1/2015 AMPICILLIN 3.6 2.4
2/1/2015 CLINDAMYCIN 2.6 4.0
2/1/2015 VANCOMYCIN 47.8 65.5
3/1/2015 AMPICILLIN 14.1 4.3
3/1/2015 CLINDAMYCIN 3.4 4.3
3/1/2015 VANCOMYCIN 62.3 79.7
[/tt]
I want my output to look like this
[tt]
Antibiotic Jan15_DOT Jan15_DDD Feb15_DOT Feb15_DDD Mar15_DOT Mar15_DDD
AMPICILLIN 24.5 82.0 2.4 3.6 4.3 14.1
CLINDAMYCIN 9.0 9.3 4.0 2.6 4.3 3.4
VANCOMYCIN 94.7 74.8 65.5 47.8 79.7 62.3
[/tt]
I am currently using this SQL I adapted from the web to static pivot the data. I see examples of dynamic pivots, but I have not seen anything on 2 columns that is at my level of understanding.
Any help would be appreciated.
You don't know what you don't know...
My data initially looks like this for 3 months.
[tt]
AbxDate Antibiotic DDD DOT
1/1/2015 AMPICILLIN 82.0 24.5
1/1/2015 CLINDAMYCIN 9.3 9.0
1/1/2015 VANCOMYCIN 74.8 94.7
2/1/2015 AMPICILLIN 3.6 2.4
2/1/2015 CLINDAMYCIN 2.6 4.0
2/1/2015 VANCOMYCIN 47.8 65.5
3/1/2015 AMPICILLIN 14.1 4.3
3/1/2015 CLINDAMYCIN 3.4 4.3
3/1/2015 VANCOMYCIN 62.3 79.7
[/tt]
I want my output to look like this
[tt]
Antibiotic Jan15_DOT Jan15_DDD Feb15_DOT Feb15_DDD Mar15_DOT Mar15_DDD
AMPICILLIN 24.5 82.0 2.4 3.6 4.3 14.1
CLINDAMYCIN 9.0 9.3 4.0 2.6 4.3 3.4
VANCOMYCIN 94.7 74.8 65.5 47.8 79.7 62.3
[/tt]
I am currently using this SQL I adapted from the web to static pivot the data. I see examples of dynamic pivots, but I have not seen anything on 2 columns that is at my level of understanding.
Code:
SELECT *
FROM
(
SELECT DISTINCT
Antibiotic
,CAST(FORMAT(AbxDate, 'MMM', 'en-US')+RIGHT(YEAR(AbxDate), 2) AS varchar(5))+CHAR(95)+col AS new_col
,value
from #asp
CROSS APPLY
(
VALUES
(DOT, 'DOT'),
(DDD, 'DDD')
) x (value, col)
) src
PIVOT
(
MAX(value)
FOR new_col in (Jan15_DOT, Jan15_DDD, Feb15_DOT, Feb15_DDD, Mar15_DOT, Mar15_DDD)
) piv
Any help would be appreciated.
You don't know what you don't know...