Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count invitation response against events and response codes

Tags:

sql

join

mysql

I have this table for Response Codes: enter image description here

And this table for invitations: enter image description here

My query so far gives this: enter image description here

While I want to achieve this: enter image description here

MY QUERY:

SELECT 
      i.eventId
     ,code.responseCode
     ,COUNT(i.attendeeResponse) responseCount
FROM invitations i
LEFT JOIN response_codes code
    ON code.responseCode = i.attendeeResponse
GROUP BY i.eventId, code.responseCode, i.attendeeResponse;

SQLFiddle

like image 235
SHAKIR SHABBIR Avatar asked Nov 20 '25 00:11

SHAKIR SHABBIR


2 Answers

You need to construct a cartesian product of all eventIds and responseCodes at first (you can achieve it with join without condition):

select c.eventId
     , c.responseCode
     , count( i.attendeeResponse ) as responseCount
from ( select distinct t1.responseCode
            , t2.eventId
       from `response_codes` t1
       join `invitations` t2 ) c
left join `invitations` i on c.responseCode = i.attendeeResponse and c.eventId = i.eventId
group by c.eventId, c.responseCode;

SQLFiddle

like image 174
potashin Avatar answered Nov 21 '25 13:11

potashin


You need to cross join the responsecode table to get the all combinations of eventid and responsecode.

SQL Fiddle

SELECT distinct
      i.eventId
     ,code.responseCode
     ,case when t.responseCount is null then 0 
      else t.responsecount end rcount
FROM invitations i
cross JOIN response_codes code
left join 
(SELECT i.eventId
       ,code.responseCode
       ,COUNT(i.attendeeResponse) responseCount
 FROM invitations i
 JOIN response_codes code
 ON code.responseCode = i.attendeeResponse
 group by i.eventid, code.responsecode) t
on t.responsecode =code.responsecode and t.eventid = i.eventid
order by i.eventid, code.responsecode desc
like image 22
Vamsi Prabhala Avatar answered Nov 21 '25 12:11

Vamsi Prabhala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!