如何将不同表中的两个字段一起添加到SQL中

时间:2015-12-21 16:20:20

标签: mysql count sum concat group-concat

我正在尝试创建一份报告,说明工作中出现问题的原因,即货物损坏,未交付等。

select
  group_concat(distinct
       concat(
        'sum((select count(jp1.MemReason) from job_pieces jp1 
         left join unapprovedquotereasons un1 on un1.Description =jp1.MemReason
         where jp1.jobid=jn.id and un1.Code=''',
         un.Code,
        '''))  AS `',
        un.Code, '`'
        )
   ) into @sql
   FROM customer c
   LEFT JOIN job_new jn ON jn.JobOwnerID = c.ID
   LEFT JOIN job_pieces jp ON jp.JobID = jn.ID
   LEFT JOIN unapprovedquotereasons un on un.Description = jp.DebriefReason
   WHERE c.Company_ID = 171;

因此,此sql语句将原因显示为标题,在此列下显示每个公司使用该原因的次数:

enter image description here

因此,在图像中我们可以看到第二家公司使用了原因"损坏"两次。 我遇到的问题是原因也保存在数据库的不同表中。所以我还需要从MemOutturnReason表中计算一个名为job_new的字段。如何将这两个字段一起添加?

生成的SQL:

select
        sum((select count(jp1.MemReason) from job_pieces jp1 
                   left join unapprovedquotereasons un1 on un1.Description =jp1.MemReason
                   where jp1.jobid=jn.id and un1.Code='DAM'))  AS `DAM`,sum((select count(jp1.MemReason) from job_pieces jp1 
                   left join unapprovedquotereasons un1 on un1.Description =jp1.MemReason
                   where jp1.jobid=jn.id and un1.Code='SIZE'))  AS `SIZE`,sum((select count(jp1.MemReason) from job_pieces jp1 
                   left join unapprovedquotereasons un1 on un1.Description =jp1.MemReason
                   where jp1.jobid=jn.id and un1.Code='GOODS'))  AS `GOODS`,sum((select count(jp1.MemReason) from job_pieces jp1 
                   left join unapprovedquotereasons un1 on un1.Description =jp1.MemReason
                   where jp1.jobid=jn.id and un1.Code='NOTREV'))  AS `NOTREV`
    FROM customer c
    LEFT JOIN job_new jn ON jn.JobOwnerID = c.ID
WHERE jn.IsActive = 1 AND c.Company_ID = 171  GROUP BY jn.JobOwnerID

1 个答案:

答案 0 :(得分:0)

我不确定数据库表中的字段,希望这会给你一个想法。这是一个伪代码。根据您的数据库表和字段

进行修改,试试这个
   SELECT c.name as Name, count(jp.MemReason) as DAMAGED, count(jp.something) as PROB
   FROM customer c
   LEFT JOIN job_new jn ON jn.JobOwnerID = c.ID
   LEFT JOIN job_pieces jp ON jp.JobID = jn.ID
   LEFT JOIN unapprovedquotereasons un on un.Description = jp.DebriefReason
   GROUP BY c.Company_ID;