我有一些問題創建查詢與此表和代碼, 我知道「GROUP BY Branch.BranchName」原因獲取多個記錄,但是,如何避免這種情況,並做在單個查詢中。 什麼,我試圖讓是 包含BRANCHNAME表 - 總payedvalue--總notpayedvalue子查詢返回多個值1與組通過
SELECT
(
SELECT SUM (DeptDesciption.DeptValue)
FROM dbo.SudentPayments
INNER JOIN dbo.Student ON dbo.SudentPayments.StudentId = dbo.Student.StudentId
INNER JOIN dbo.DeptDesciption ON SudentPayments.DeptDesciptionId = DeptDesciption.DeptDesciptionId
INNER JOIN dbo.Branch on dbo.Branch.BranchId = Student.BranchId
WHERE SudentPayments.IsDeptPayed = 0
GROUP BY Branch.BranchName
) AS Payed,
(
SELECT SUM (DeptDesciption.DeptValue)
FROM dbo.SudentPayments
INNER JOIN dbo.Student ON dbo.SudentPayments.StudentId = dbo.Student.StudentId
INNER JOIN dbo.DeptDesciption ON SudentPayments.DeptDesciptionId = DeptDesciption.DeptDesciptionId
INNER JOIN dbo.Branch on dbo.Branch.BranchId = Student.StudentId
WHERE SudentPayments.IsDeptPayed = 1
GROUP BY Branch.BranchName
) AS Notpayed,
Branch.BranchName
FROM dbo.SudentPayments
INNER JOIN dbo.Student ON dbo.SudentPayments.StudentId = dbo.Student.StudentId
INNER JOIN dbo.DeptDesciption ON SudentPayments.DeptDesciptionId = DeptDesciption.DeptDesciptionId
INNER JOIN dbo.Branch on dbo.Branch.BranchId = Student.StudentId
首先要做的就是停止使用相關的子查詢,因爲它們是性能豬!改用連接,派生表或CTE。這是一個需要打破的SQL反模式。 – HLGEM