Jump to content

MySQL grouping functions


warden

Recommended Posts

Hey guys,

 

I have a query like this:

 

select st.caretype,SUM(IF( ((q.name = "Question1" AND sa.answer = 'Y')

OR (q.name = "Question2")),1,0)) qcnt from staff st

inner join staffanswer sa on sa.staff_id=st.id

inner join question q on q.id = sa.question_id

group by caretype

;

 

This gives me a result set:

+----------+-------------------+

| caretype | count(staff_id)/2 |

+----------+-------------------+

|        3 |            1.0000 |

|        1 |            1.0000 |

|        3 |            1.0000 |

+----------+-------------------+

 

 

The problem is that I want it grouped by care type and I can't do SUM(COUNT(( ...

Any hints?

 

The problem solved in this query is:

Get all the number of *pairs* (so double records from q table for each of staff.id) and group them by caretype from staff table.

Link to comment
https://forums.phpfreaks.com/topic/105403-mysql-grouping-functions/
Share on other sites

Ok , I'm almost there with a result

 

+----------+---------------------------+

| caretype | IF(count(staff_id)=2,1,0) |

+----------+---------------------------+

|        3 |                        0 |

|        3 |                        0 |

|        3 |                        1 |

|        3 |                        0 |

|        1 |                        1 |

|        3 |                        1 |

+----------+---------------------------+

 

with query:

 

select caretype,IF(count(staff_id)=2,1,0) from staffanswer sa

inner join question q on sa.question_id=q.id

inner join staff st on st.id = sa.staff_id

where

((q.name = "Question1" AND sa.answer = 'Y')

OR (q.name = "Question2"))

group by staff_id;

 

But i want now to sum the values of IF like

select caretype,SUM(IF(count(staff_id)=2,1,0)) from staffanswer sa

inner join question q on sa.question_id=q.id

inner join staff st on st.id = sa.staff_id

where

((q.name = "Question1" AND sa.answer = 'Y')

OR (q.name = "Question2"))

group by staff_id;

 

but it says invalid use of group function :(

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.