Question

OK, so I have this query to find number of types per day like below. (Courtesy of MarkD here Counting Items/Rows in DB as Columns Grouped by Another Column)

 select type,
           sum(case when MyDate = '' then 1 else 0 end) as "10/1",
           sum(case when MyDate = '' then 1 else 0 end) as "10/2
           ...etc
 from MyTabe
 group by type

However, I want to dynamically create date columns and have the count generated for each column, otherwise I would end up manually adding a new column for each day of the month.

Was it helpful?

Solution

I guess the best way to get the output I wanted was to do the following:

 define startDate = to_date('2013-10-01', 'yyyy-mm-dd')
 select type,
       sum(case when MyDate = &&startDate then 1 else 0 end) as "1"
       , sum(case when MyDate = &&startDate +1 then 1 else 0 end) as "2"
       , sum(case when MyDate = &&startDate +2 then 1 else 0 end) as "3"
       , sum(case when MyDate = &&startDate +3 then 1 else 0 end) as "4"
       ...etc for as many days of current month I am running
       , sum(case when MyDate = &&startDate +29 then 1 else 0 end) as "30"   
       , sum(case when MyDate = &&startDate +30 then 1 else 0 end) as "31"--This would be commented out for Nov  
 from MyTabe
 group by type
 order by type
 ;

This way if I want to run this for Nov, Dec, Jan, and so on, I can just change the variable at the top and run the query. This is what I was looking for; however, I still wonder if it would be possible to generate the columns dynamically, but the more I look at it, the more I think that would require a pivot table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top