So what i’m trying to do left join this table that would define what a question is from the questions table and check with the responses table.
I wrote the left join to define each question as its own column but its not working.. any ideas?
select *
FROM Leads l
/*JOIN Projects P ON L.projectid=P.projectid
JOIN Leads LE ON LE.LISTID=L.listid
JOIN Calls CA ON CA.LEADID=LE.leadid*/
join Lists li on (li.Listid=l.Listid)
JOIN Projects P ON (Li.projectid=P.projectid)
join Calls ca on (ca.leadid=l.leadid)
LEFT JOIN (
SELECT
leadid,
Authorized=MIN(CASE qname WHEN 'Authorized' THEN RESPONSE END),
ReplacementName=MIN(CASE qname WHEN 'ReplacementName' THEN RESPONSE END),
SpokeToGroup=MIN(CASE qname WHEN 'SpokeToGroup' THEN RESPONSE END),
SpokeToName=MIN(CASE qname WHEN 'SpokeToName' THEN RESPONSE END),
SpokeToTitle=MIN(CASE qname WHEN 'SpokeToTitle' THEN RESPONSE END),
WishToRecieve=MIN(CASE qname WHEN 'WishToRecieve' THEN RESPONSE END),
Question01=MIN(CASE qname WHEN 'Question01' THEN RESPONSE END),
... -- lots of other fields
MAGExpiration=MIN(CASE qname WHEN 'MAGExpiration' THEN RESPONSE END),
SourceGroup=MIN(CASE qname WHEN 'SourceGroup' THEN RESPONSE END),
SourceID=MIN(CASE qname WHEN 'SourceID' THEN RESPONSE END),
ClientOtherID=MIN(CASE qname WHEN 'ClientOtherID' THEN RESPONSE END)
from Questions q join Responses r on (r.questionid=q.questionid)
)
Your subquery missing a
GROUP BY:You are using all of the aggregate functions but you are not grouping by anything.
You should also include an
ELSEon yourCASEstatements.There might be better ways for you to perform this. If you are using SQL Server, then you can perform this much easier using the
PIVOTfunction. Since you have so many fields that you are attempting to pivot, you should look at using dynamic SQL in sql server and prepared statements in MySQL.Edit #1, you also appear to be missing a few key items: