我试图从两个表(具有如下所示的归档和项目)中获得结果,这些表具有来自两个不同表的规定。我们要从存档和项目(具有完全相同的字段)中获取Designer,ProjectNum和总金额。存档和项目中有一个名为customerEmail的字段,我想使用该字段排除另一个表中的任何文件,这些表称为profile(作为customerEmail),并且customerStatus为“已取消”。我还想从另一个名为changeorder的表中获取change_total,该表具有与存档和项目相同的ProjectNum。

首先,我使用UNION将项目和归档文件整合在一起,并添加了代码,以删除“已取消”的项目

 SELECT DISTINCT(designerName),
        SUM(total),
        SUM(amount)
 FROM
 (
   SELECT DISTINCT(Building_designer) as designerName,
          COUNT(DISTINCT(Project_Num))as total,
          SUM(archive.total_amount) as amount
   FROM `archive`
   INNER JOIN profiles
     ON archive.customer_email = profiles.customer_email
   WHERE profiles.customer_status != "Cancelled"
   AND SUBSTRING(archive.Project_Num,1,2)=17
   GROUP BY designerName

   UNION

   SELECT DISTINCT(Building_designer) as designerName,
          COUNT(DISTINCT(Project_Num))AS total,
          SUM(projects.total_amount) AS amount
   FROM `projects`
   INNER JOIN profiles
     ON projects.customer_email = profiles.customer_email
   WHERE profiles.customer_status != "Cancelled"
   AND SUBSTRING(projects.Project_Num,1,2)=17
   GROUP BY designerName
 ) AS temp
 GROUP BY designerName


我正在尝试从名为changeorder的表中获取totalAMOUNT。最好再进行一次联接以包含该表吗?

这是一个无需添加到该语句即可工作的示例

SELECT SUM(DISTINCT(change_total))
FROM `changeorder`
WHERE SUBSTRING(project_num,1,2)=17


为什么我需要添加其他两个表,是因为它也跟踪“已取消”的内容。所以我需要总结与每个人相关的所有项目号的change_total

最佳答案

谨防。不到两个月前,我从“ Hello World”开始编码。

如果我对您的理解正确,那么您正在寻找三个“数据集”:
1)设计器,ProjectNum和来自归档的total_amount
2)设计器,ProjectNum和来自项目的total_amount
3)change_total来自变更单

您希望从前两个中消除取消客户状态的情况(在另一个表中)。

如果一切正确,请尝试:

SELECT a.Designer, a.ProjectNum, a.total_amount,
        prjct.Designer, prjct.ProjectNum, prjct.total_amount,
        chgOrd.change_total
    -- the first two JOINs are to enable the WHERE later for knocking out
FROM archive a JOIN profiles prf ON a.customerEmail = prf.customerEmail,
              projects prjct JOIN profiles prf ON prjct.customerEmail = prf.customerEmail
    -- then another (double) JOIN to link changeorder properly to archive and project
              changeorder chgOrd JOIN a ON chgOrd.ProjectNum = a.ProjectNum
                                  JOIN prjct ON chgOrd.ProjectNum = prjct.ProjectNum
 WHERE prf.customerStatus <> "Cancelled"


我希望我是对的,您可以在FROM末尾的JOIN中使用在FROM开头创建的别名。

09-27 21:38