You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL或Power BI中创建计算行?SQL查询新增利润行实现方法

SQL查询新增利润汇总行实现方案

该需求可直接通过标准SQL语法实现,以下提供两种兼容不同场景的方案:

方案1:UNION ALL 拼接(全数据库兼容)

该方案不依赖数据库高阶特性,所有支持标准SQL的数据库均可运行,改造后代码如下:

SELECT a.pcg_type GL_Acoount_Group,
     Abs(sum(b.debit-b.credit)) GL_Amount
FROM dolibarr.llx_accounting_account a
JOIN dolibarr.llx_accounting_bookkeeping b
  ON a.account_number = b.numero_compte
WHERE a.pcg_type IN ('INCOME', 'EXPENSE')
    AND a.fk_pcg_version = 'PCG99-BASE'
GROUP BY a.pcg_type

UNION ALL

-- 拼接利润计算行
SELECT 'PROFIT' GL_Acoount_Group,
    (
        SELECT Abs(sum(b.debit-b.credit))
        FROM dolibarr.llx_accounting_account a
        JOIN dolibarr.llx_accounting_bookkeeping b ON a.account_number = b.numero_compte
        WHERE a.pcg_type = 'INCOME' AND a.fk_pcg_version = 'PCG99-BASE'
    ) - (
        SELECT Abs(sum(b.debit-b.credit))
        FROM dolibarr.llx_accounting_account a
        JOIN dolibarr.llx_accounting_bookkeeping b ON a.account_number = b.numero_compte
        WHERE a.pcg_type = 'EXPENSE' AND a.fk_pcg_version = 'PCG99-BASE'
    ) GL_Amount

运行上述代码即可直接输出包含收入、支出、利润三行的预期结果。

方案2:ROLLUP 分组汇总(支持高阶分组的数据库可用)

如果你使用的是MySQL 8.0+、PostgreSQL、Oracle等支持ROLLUP分组语法的数据库,可以使用更简洁的写法,避免重复执行主查询:

SELECT 
    IF(GROUPING(a.pcg_type) = 1, 'PROFIT', a.pcg_type) GL_Acoount_Group,
    IF(
        GROUPING(a.pcg_type) = 1,
        SUM(IF(a.pcg_type = 'INCOME', ABS(b.debit - b.credit), -ABS(b.debit - b.credit))),
        ABS(SUM(b.debit - b.credit))
    ) GL_Amount
FROM dolibarr.llx_accounting_account a
JOIN dolibarr.llx_accounting_bookkeeping b ON a.account_number = b.numero_compte
WHERE a.pcg_type IN ('INCOME', 'EXPENSE')
    AND a.fk_pcg_version = 'PCG99-BASE'
GROUP BY a.pcg_type WITH ROLLUP

内容的提问来源于stack exchange,提问作者user12469157

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:09:03