SQL query to get the subtotal of some rows

会有一股神秘感。 提交于 2019-12-04 17:18:47

You can aggregate using a CASE expression, which forms a group using the id if the manager_id be zero, otherwise using the manager_id. The rest of the logic is similar to what you already have.

SELECT
    CASE WHEN manager_id = 0 THEN id ELSE manager_id END AS manager_id,
    MAX(CASE WHEN is_manager=1 THEN name END) AS name,
    SUM(no_of_items) AS total_items,
    SUM(revenue) AS total_revenue
FROM items_revenue
GROUP BY
    CASE WHEN manager_id = 0 THEN id ELSE manager_id END;

Demo

One side note: I used a function in the GROUP BY clause, which is not ANSI compliant and therefore may not run everywhere. To fix this, we can first subquery your table to generate the effective manager groups. Then, use my above answer against this intermediate result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!