views:

39

answers:

2

Currently I am doing one query, with 3 sub queries,
all queries are on the same table,
all queries have different where clauses

I have thought about doing a group by however this would destroy the SUM()

here is the query

SELECT SUM(club) AS club, 
(SELECT COUNT(id) FROM action_6_members WHERE SUBSTR(CODE, 1, 1) = '9') AS 5pts,
(SELECT COUNT(id) FROM action_6_members WHERE SUBSTR(CODE, 1, 1) = 'A') AS 10pts,
(SELECT COUNT(id) FROM action_6_members WHERE SUBSTR(CODE, 1, 1) NOT IN('9', 'A')) AS General
FROM action_6_members;

here is the explain

id  select_type  table             type  rows  Extra        
1   PRIMARY      action_6_members  ALL   1471               
4   SUBQUERY     action_6_members  ALL   1471  Using where  
3   SUBQUERY     action_6_members  ALL   1471  Using where  
2   SUBQUERY     action_6_members  ALL   1471  Using where  
A: 

Tweak this:

SELECT SUM(club) as club, COUNT(1) FROM action_6_members GROUP BY SUBSTR(CODE, 1, 1)
Matt Williamson
I thought of doing something like that,But then i end up with hundreds of rows, all with a partial value for club, and, i need any codes that dont start with 9 or a grouped as one group
Hailwood
I could do it like this:`SELECT SUM(club) AS club, COUNT(1) FROM action_6_members GROUP BY IF(SUBSTR(CODE, 1, 1) = 9, 1, IF(SUBSTR(CODE, 1, 1) = 'A', 2, 3));` but then i still end up with partial values for the sum
Hailwood
+3  A: 

Use:

SELECT SUM(club) AS club, 
       SUM(CASE WHEN SUBSTR(CODE, 1, 1) = '9' THEN 1 ELSE 0 END) AS 5pts,
       SUM(CASE WHEN SUBSTR(CODE, 1, 1) = 'A' THEN 1 ELSE 0 END) AS 10pts,
       SUM(CASE WHEN SUBSTR(CODE, 1, 1) NOT IN('9', 'A') THEN 1 ELSE 0 END) AS General
  FROM action_6_members;
OMG Ponies