I tried different approaches but even though I think my syntax is ok the query doesn't work.
I have a fairly complicated polls system. In general every answer to poll is putted into one table
CREATE TABLE `polls` (
`poll_id` int(10) NOT NULL auto_increment,
`client_id` int(10) NOT NULL,
`key` varchar(20) NOT NULL,
`val` varchar(30) NOT NULL,
PRIMARY KEY (`poll_id`)
);
The 'key' column is like ID of certain question (like for 'How often do you drink coffee' the key would be 'coffee'), the value varies depending on the question - sometimes is 0 or 1, sometimes is 0-6, sometimes it's some string. For statistical purposes I want to display the percentage of every answer for every question. I use this query for that:
SELECT p.`key`, p.val, COUNT(p.poll_id) AS people,
(SELECT COUNT(client_id) FROM clients) AS total
FROM polls AS p GROUP BY p.`key`, p.val ORDER BY p.`key`, p.val
The problem in this query is that I depend on clients table to get the total count of users - which worked when every user answered every question. Now we added one more question to the poll and the query doesn't work how it should, because now not every user answered that question but the percentage is counted like every user did answer.
I tried modifying the query to something like this (I tried different ways, but let's say came to that):
SELECT p.`key`, p.val, COUNT(p.poll_id) AS people,
(SELECT COUNT(p2.poll_id) FROM polls AS p2 WHERE p2.`key` = p.`key`) AS total
FROM polls AS p GROUP BY p.`key`, p.val ORDER BY p.`key`, p.val
The way I see it - it should get all the values from the main query, group it and then execute the subquery - so I would get something like:
coffee , 0 , 10 , 30
coffee , 1 , 15 , 30
coffee , 2 , 5 , 30
tea , 0 , 5 , 25
tea , 1 , 5 , 25
tea , 3 , 5 , 25
tea , 4 , 10 , 25
The last column would count all rows that have the same key and ignore the val column (for coffee -> 10 + 15 + 5 = 30, for tea -> 5 + 5 + 5 + 10 = 25). The query doesn't execute. It's running and running and running and eventually I have to cancel it. I sense that the problem is in the "p2.key
= p.key
" part of the subquery, because if I write "p2.key
= 'coffee'" the query runs like a charm.