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
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 :(

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.