I have a simple database (using MySql) with which I need to generate a report.
I have a table that contains weekly logs which are submitted by users. Each of these logs have states, such as: submitted, approved, etc.
LogSubmissions Table +----+--------+--------+---------+-------+ | id | weekId | userId | info... | state | +----+--------+--------+---------+-------+ | 0 | 0 | 1 | data... | 0 | | 1 | 0 | 2 | data... | 1 | | 1 | 0 | 3 | data... | 1 | | 2 | 1 | 1 | data... | 0 |
I also have a table which keeps track of the weeks.
WeekManager Table +----+-----------+---------+---------+ | id | startDate | EndDate | ... | +----+-----------+---------+---------+ | 0 | Date1 | Date2 | ... | | 1 | Date3 | Date4 | ... | | 2 | Date5 | Date6 | ... |
I need a report which displays the weeks as columns as well as the names from a user table. It should display the state of the weekly log the user submitted. For example Bob submission for Week 1 has a state of 0.
Report +------+--------+--------+--------+-------+ | Name | Week 1 | Week 2 | Week 3 | ... | +------+--------+--------+--------+-------+ | Bob | 0 | 1 | 0 | ... | | Joe | 1 | 1 | 1 | ... | | Jim | 0 | 0 | 0 | ... |
I am having a bit of trouble getting this report working. My major obstacle is that weeks are added, so the amount of columns for report will vary.
This here helped quite a bit, however it only deals with a static amount of rows. I need something that varies depending on the amount of weeks. I was thinking of using a loop of some kind to achieve this, however I’m not sure if that is possible.
Any help would be appreciated, thank you.
User Table:
User Table +----+------+---------+ | id | name | ... | +----+------+---------+ | 0 | ... | ... | | 1 | ... | ... | | 2 | ... | ... |
Your table structure is not exactly clear (for example I don’t see where you get
user name).The basic set up for a pivot in MySQL uses an aggregate function and a
CASEexpression similar to this:See SQL Fiddle with Demo.
Edit, if you have an unknown number of weeks then you can use a prepared statement to generate dynamic sql:
See SQL Fiddle with Demo