SQL JOIN, GROUP BY on three tables to get totals

前端 未结 5 1084
攒了一身酷
攒了一身酷 2020-12-14 21:17

I\'ve inherited the following DB design. Tables are:

customers
---------
customerid  
customernumber

invoices
--------
invoiceid  
amount

invoicepayments
         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 21:22

    I have a tip for those, who want to get various aggregated values from the same table.

    Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).

    Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points) AND then by SUM(points WHERE type = x). That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).

    The SQL would be:

    SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
    FROM user
    LEFT JOIN points ON user.id = points.user_id
    GROUP BY user.id
    

    The beauty of this is in the SUM(points.points * (points.type = 7)) where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.

提交回复
热议问题