I have a really complicated SQL question for a mySQL database. I will first introduce all needed tables for this question:
User Table:
Id date_created
------------------------------
1 2015-09-19T14:18:07.000Z
2 2015-09-20T01:16:34.000Z
3 2015-09-21T15:10:21.000Z
…
Setting table:
Id User_id setting_key setting_value
----------------------------------------------
1 1 city 1
2 3 city 2
3 2 city 1
…
City names Table:
Id name
------------------
1 New York
2 Los Angeles
3 Boston
…
With a select-query I Would like to achieve this:
date New York Los Angeles Boston …
------------------------------------------------------
2015-09-19 1 0 0
2015-09-20 2 0 0
2015-09-21 2 1 0
…
For every date in certain range how many users has as setting New york, Los, Angeles.... The only thing I can achieve is this query:
select date(u.date_created), n.name, count(u.id)
from user u inner join setting s
on u.id = s.user_id
and setting_key = 'city'
inner join name n
on s.setting_value = n.id
where u.date_created > '2015-09-19T14:18:07.000Z'
group by 1, 2
but then I get this result:
date name count
-------------------------------
2015-09-19 New York 1
2015-09-19 Los Angeles 0
2015-09-19 Boston 0
2015-09-20 New York 1
2015-09-20 Los Angeles 0
2015-09-20 Boston 0
2015-09-21 New York 0
2015-09-21 Los Angeles 1
2015-09-21 Boston 0
…
It is not cummulative en there is row for each city instead of a column for each city. Does somebody know (the complicated) answer? If something is not clear just ask, In real live these are tables of 50.000 rows and I can't change the structure, I need this query for analytics purposes