MySQL Query for book cost of a class

后端 未结 6 764
清酒与你
清酒与你 2021-01-21 17:39

I just need a single MySQL line query for the following.

Lets say there are 2 simple tables: Class and Books<

相关标签:
6条回答
  • 2021-01-21 18:08

    Something like this:

    select c.classId, sum(b.cost) as TotalCost,sum(c.students) as TotalStudents from books as b, class as c where b.classId = class.Id and c.Id = YourKnowClassId group by c.Id;
    
    0 讨论(0)
  • 2021-01-21 18:08

    Did you mean something like:

    SELECT C.Name AS ClassName, SUM(B.Price) * C.Students AS BookCost
      FROM Class AS C INNER JOIN
           Books AS B ON C.ID = B.ClassId
      WHERE C.ID IN (SELECT ID
                       FROM Class
                       WHERE Students >= 31
                       ORDER BY Students ASC
                       LIMIT 1)
      GROUP BY C.ID;
    
    0 讨论(0)
  • 2021-01-21 18:09

    This should do the trick:

    SELECT SUM(cost) AS cost FROM Books WHERE ClassId=? GROUP BY ClassId

    Where the question makr is either the ID of the class or part of a prepared statement where you feed it the class ID.

    You can retrieve the sum with column name "cost".

    0 讨论(0)
  • 2021-01-21 18:12
       SELECT c.Name,
              SUM(b.Price * c.Students) cost
         FROM Class c
    LEFT JOIN Books b ON b.ClassId = c.ID
        WHERE c.Students >= 31
     GROUP BY c.ID
    
    0 讨论(0)
  • 2021-01-21 18:15
    select min(c.Name) as Name, sum(b.Price * c.Students) as Cost
    from Class c
    left join Books b on b.ClassId = c.ID
    where c.Students >= 31
    group by c.ID
    
    0 讨论(0)
  • 2021-01-21 18:19

    Try this:

    In Single Line:

    SELECT SUM(Class.Students * Books.Cost) AS BookCost  FROM Books INNER JOIN Class       ON Books.ClassId = Class.ClassId WHERE Books.ClassId = <CLASS-ID-VALUE>  GROUP BY Books.ClassId
    

    With formatting:

    SELECT SUM(Class.Students * Books.Cost) AS BookCost
      FROM Books INNER JOIN Class
       ON Books.ClassId = Class.ClassId
    WHERE Books.ClassId = <CLASS-ID-VALUE>
    GROUP BY Books.ClassId
    
    0 讨论(0)
提交回复
热议问题