Subquery Returned More Than 1 Value with the Group By

后端 未结 2 539
面向向阳花
面向向阳花 2021-01-23 01:50

I have some problem creating query with this tables and codes, I know \"GROUP BY Branch.BranchName\" cause to get multiple records,but,How can avoid this and to do that in sing

2条回答
  •  逝去的感伤
    2021-01-23 02:08

    Try this one -

    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
    

    UPDATE:

    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
    

提交回复
热议问题