I have the following table:
id | billingno | location
-------------------------
1 | 9999999 | Toronto
2 | 9999999 | Toronto
3 | 7777777 | Toronto
4 | 7777777 | Quebec
I need a query that would generate me something that looked like this:
location | total | display
--------------------------
Toronto | 3 | 9999999 - 2, 7777777 - 1
Quebec | 1 | 7777777 - 1
So, it groups by location, displays the total number of billingno’s for that location, and then the display column lists each billingno and how many times they were in that location. I have been trying to write this for some time, my closest attempt is this:
SELECT location, COUNT(*) AS total, GROUP_CONCAT(DISTINCT CAST(CONCAT(CONVERT(billingno,CHAR(16)), ' - ', THIS_COUNT_PART_FOR_EACH_LOCATION_IN_DISPLAY_DOESNT_WORK)AS CHAR)
SEPARATOR ' - ') AS display
FROM table GROUP BY location
ORDER BY COUNT(*) DESC
It gives me everything I need except I cannot for the life of me figure out how to count the number of each billingno’s under display. If I use COUNT() it gives me an error about grouping. Please help!
Oh, I also had to use the convert to char so it would show up as text and not a BLOB in phpMyAdmin. Thanks again!
Sample data:
Query:
Result: