使用Group By返回超过1个值的子查询

sak*_*kir 2 sql sql-server

我有一些问题用这个表和代码创建查询,我知道"GROUP BY Branch.BranchName"导致获得多个记录,但是,如何避免这种情况并在单个查询中执行此操作.我想要得到的是一个包含BranchName的表 - total paidedvalue-- 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
Run Code Online (Sandbox Code Playgroud)

Dev*_*art 5

试试这个 -

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
Run Code Online (Sandbox Code Playgroud)

更新:

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
Run Code Online (Sandbox Code Playgroud)