I have a table containing lots of data with several fields including:
day (Monday ~ Sunday)
City (NY, LA, FL, etc.)
I would like to use php to make a table to display totals like this:
--- Mon --- Tue --- Wed ...
NY 6 8 9
LA 7 5 3
FL 1 0 4
But I am having trouble to write the SQL to make this work. I have used union but that appends the result at the bottom, so it seems I need to use inner join, or not even it. The two queries that I can get remotely close to what I want are:
select city, count(id) as 'Monday' from
index
where city = "NY" and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index
where city = 'LA' and day = 'Monday' group by city
union all
select city, count(id) as 'Monday' from index
where city = 'FL' and day = 'Monday' group by city
This produces the following result
--- Mon
NY 6
LA 7
FL 1
The problem with this is I don't know how to add the rest of the days to the right of it
Another query I have tried is select a.day, a.counts as 'NY', b.counts as 'LA' from
(select day, count(id) as counts from index
where city='NY' GROUP BY DAY) as a
left join
(select day, count(id) as counts from index
where city='LA' GROUP BY DAY) as b
on (a.day = b.day)
order by field (a.day
, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
This produces the following result
NY --- LA ---
Monday 6 7
Tuesday 8 5
And the problem with this one is the row and column should be swapped, also I don't know how to add another city (I have many cities).
All the data is in one table called "index". Could someone give me the guidance on how to write the SQL? I would also need the field to show 0 or Null when there is no record. The end goal is to produce the table with PHP.
Thank you for taking the time to read and answer.
select city, count(id) as 'count' from index where city IN('NY','LA','FL') and day IN('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') group by city
– Anant Kumar Singh