In some application,
I am using following sql query,
SELECT DATE,
SUM( CASE WHEN project_id = '6' THEN spent_time ELSE 0 END ) project_1,
SUM( CASE WHEN project_id = '41' THEN spent_time ELSE 0 END ) project_2,
SUM( CASE WHEN project_id = '14' THEN spent_time ELSE 0 END ) project_3
FROM tasks
WHERE user_id =80
GROUP BY DATE, project_id
it returns following output

but in the above SQL query I have used predefined columns. I am looking for a solution where I have dynamic columns say I don’t have project ids known before hand.
Also I want one extra columns that shows sum of project_1, project_2, project_3 for each row.
So, the resultant structure will be DATE, PROJECT_1, PROJECT_2, PROJECT_3, SUM_OF_PROJECTS
Can I also get data where the row doesn’t exists? For instance 2012-04-03 in the below example.Preferably not using calendar table
Any pointers would be appreciated.
other details: Database- mysql, Rails(2.3.14)
You need to write code the writes SQL. There is no way to have a single static SQL query that returns a dynamic number of columns. Only by dynamically building the query itself can you accomplish that.
Your example code is fine. For a fixed number of projects.
You could even make ‘6’, ’41’ and ’14’ into parameters, meaning that your query will always return three projects, but they could be different projects each time.
But to then have a fourth project, you’d need to change the query.
You could write code to make that change on the fly (dynamic SQL), or just work out the most columns you ever need at once, and then live with that limitation.