我在使用此表和代码创建查询时遇到了一些问题, 我知道“GROUP BY Branch.BranchName”导致获得多条记录,但是,如何避免这种情况并在单个查询中做到这一点。 我想要得到的是一张 table contains BranchName -- total payedvalue-- total notpayedvalue
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
最佳答案
试试这个 -
SELECT
b.BranchName
, Notpayed = SUM(CASE WHEN sp.IsDeptPayed = 1 THEN d.DeptValue END)
, Payed = SUM(CASE WHEN sp.IsDeptPayed = 0 THEN d.DeptValue END)
FROM dbo.SudentPayments sp
JOIN dbo.Student s ON sp.StudentId = s.StudentId
JOIN dbo.DeptDesciption d ON sp.DeptDesciptionId = d.DeptDesciptionId
JOIN dbo.Branch b on b.BranchId = s.StudentId
GROUP BY ALL b.BranchName
更新:
SELECT
b.BranchName
, Notpayed = ISNULL(t.Notpayed, 0)
, Payed = ISNULL(t.Payed, 0)
FROM dbo.Branch b
LEFT JOIN (
SELECT
s.StudentId
, Notpayed = SUM(CASE WHEN sp.IsDeptPayed = 1 THEN d.DeptValue END)
, Payed = SUM(CASE WHEN sp.IsDeptPayed = 0 THEN d.DeptValue END)
FROM dbo.SudentPayments sp
JOIN dbo.Student s ON sp.StudentId = s.StudentId
JOIN dbo.DeptDesciption d ON sp.DeptDesciptionId = d.DeptDesciptionId
GROUP BY s.StudentId
) t on b.BranchId = s.StudentId
关于sql - 子查询通过 Group By 返回了超过 1 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17323954/