且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL查询以获取某些行的小计

更新时间:2023-01-21 10:30:41

您可以使用CASE表达式进行汇总,如果manager_id为零,则使用id表达式形成一个组,否则使用manager_id .其余逻辑与您已经拥有的逻辑相似.

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;

演示

一个侧面说明:我在GROUP BY子句中使用了一个函数,该函数不符合ANSI,因此可能无法在所有地方运行.要解决此问题,我们可以首先对您的表进行子查询以生成有效的经理组.然后,将我上面的答案用于此中间结果.

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.