我想從兩個表(歸檔和項目,如下所示)得到兩個不同表的規定的結果。我們希望從檔案和項目(它們具有完全相同的字段)中獲取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
如果你格式化的話,SQL很容易調試 – JohnHC
另外,如果你打算把GROUP BY變成列,你不需要DISTINCT – JohnHC