1

所以我想做的左加入这个表,它将定义问题表中的问题并检查响应表。我写了左连接将每个问题定义为自己的列,但它不起作用..有什么想法吗?

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)
)
4

1 回答 1

3

您的子查询缺少GROUP BY

GROUP BY leadid

您正在使用所有聚合函数,但没有按任何内容进行分组。

你还应该ELSE在你的CASE陈述中加入一个。

您可能有更好的方法来执行此操作。如果您使用的是 SQL Server,那么您可以使用该PIVOT函数更轻松地执行此操作。由于您有很多字段要尝试进行透视,因此您应该考虑在 sql server 中使用动态 SQL 并在 MySQL 中使用准备好的语句。

编辑#1,您似乎还缺少一些关键项目:

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,
    MIN(CASE qname WHEN  'Authorized' THEN RESPONSE END) as Authorized,
    MIN(CASE qname WHEN 'ReplacementName' THEN RESPONSE END) as ReplacementName,
    MIN(CASE qname WHEN 'SpokeToGroup' THEN RESPONSE END) as SpokeToGroup,
    MIN(CASE qname WHEN 'SpokeToName' THEN RESPONSE END) as SpokeToName,
    MIN(CASE qname WHEN 'SpokeToTitle' THEN RESPONSE END) as SpokeToTitle,
    MIN(CASE qname WHEN 'WishToRecieve' THEN RESPONSE END) as WishToRecieve,
    MIN(CASE qname WHEN 'Question01' THEN RESPONSE END) as Question01,
    ... -- lots of other fields
    MIN(CASE qname WHEN 'MAGExpiration' THEN RESPONSE END) as MAGExpiration,
    MIN(CASE qname WHEN 'SourceGroup' THEN RESPONSE END) as SourceGroup,
    MIN(CASE qname WHEN 'SourceID' THEN RESPONSE END) as SourceID,
    MIN(CASE qname WHEN 'ClientOtherID' THEN RESPONSE END) as ClientOtherID
  from Questions q 
  join Responses r 
    on (r.questionid=q.questionid)
  group by leadid
) qr  -- an alias for the subquery
  on l.leadid = qr.leadid  -- the on for the join 
于 2012-12-21T18:25:04.007 回答