mysql - Add empty date row to query result -
there 6 kind of ticket types. user enter starting date , ending date. have show how many each type of tickets on each days between 2 date.
ticket table: id (int), type_id (int), created_at (date), , more fields
input: date_begin, date_end
output: rows > dates. columns > date, total_amount, , each types
my current query:
select date(ticket.created_date) date, sum(if(ticket.created_date, 1, 0)) total, sum(if(ticket.type_id null, 1, 0)) total0, sum(if(ticket.type_id = 1, 1, 0)) total1, sum(if(ticket.type_id = 2, 1, 0)) total2, sum(if(ticket.type_id = 3, 1, 0)) total3, sum(if(ticket.type_id = 4, 1, 0)) total4, sum(if(ticket.type_id = 5, 1, 0)) total5 ticket join ticket_type on ticket_type.id = ticket.type_id date(ticket.created_date) between '2015-06-12' , '2015-06-22' group date(ticket.created_date) current output:

desired output:

as see today 2015-06-19. database have data until right (today). if user's end_date in future, want rows until day, , datas 0.
first of must create funcion "explodedates". have example of definition on link on previous coment. however, if using sqlserver, can use code:
create function explodedates(@firstdate date, @seconddate date) returns @mytable table ( mydate date ) begin while @firstdate < @seconddate begin insert @mytable(mydate) values (@firstdate); set @firstdate = dateadd(day, 1, @firstdate); end return end go when had defined function, can call this:
select * dbo.explodedates('01/01/2015', '31/01/2015') after you, have define initial query this:
select d.mydate date, sum(if(ticket.created_date, 1, 0)) total, sum(if(ticket.type_id null, 1, 0)) total0, sum(if(ticket.type_id = 1, 1, 0)) total1, sum(if(ticket.type_id = 2, 1, 0)) total2, sum(if(ticket.type_id = 3, 1, 0)) total3, sum(if(ticket.type_id = 4, 1, 0)) total4, sum(if(ticket.type_id = 5, 1, 0)) total5 dbo.explodedates('12/06/2015', '22/06/2015') d left join ticket t on t.created_date = d.mydate left join ticket_type on ticket_type.id = ticket.type_id group d.mydate
Comments
Post a Comment