2017-06-14 152 views
0

我想從兩個表(歸檔和項目,如下所示)得到兩個不同表的規定的結果。我們希望從檔案和項目(它們具有完全相同的字段)中獲取Designer,ProjectNum和Total Amount。歸檔文件和項目有一個名爲customerEmail的字段,我想用它來排除名爲profiles(其爲customerEmail)的不同表中的任何內容,這些表的customerStatus爲「已取消」。我還想從另一個名爲changeorder的表中獲取change_total,該表具有與歸檔和項目相同的ProjectNum。多表SQL SELECT語句

我第一次使用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得到總金額的項目。是否最好做另一個連接來包含表格?

這裏是它的一個例子,而不將其添加到這個聲明

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

工作爲什麼我需要添加其他兩個表是它跟蹤的東西都是「已取消」爲好。所以我需要爲每個人關聯的所有項目編號加上change_total

+0

如果你格式化的話,SQL很容易調試 – JohnHC

+0

另外,如果你打算把GROUP BY變成列,你不需要DISTINCT – JohnHC

回答

1

請注意。不到兩個月前,我開始從「Hello World」編碼。

如果我理解正確的話,你要尋找的三個 '套' 的數據: 1)設計,ProjectNum和歸檔 TOTAL_AMOUNT 2)設計,ProjectNum和項目 TOTAL_AMOUNT從changeorder

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" 

我希望我是對的,你可以在使用的開始創建的別名從加入以它的結束。