简体   繁体   English

如何在 sql 或 power bi 中创建计算行?

[英]How to create a calculated row in sql or power bi?

I am trying to do a calculation on 2 rows on a SQL I wrote so I can have a 3 row that will be Profit and show the amount is it possible ?我正在尝试对我写的 SQL 的 2 行进行计算,这样我就可以有3 行将是利润并显示金额是否可能

This dummy data not true to any company!这个虚拟数据对任何公司都不真实!

see below:见下文:

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')
    ANDa.fk_pcg_version = 'PCG99-BASE'
GROUP BY a.pcg_type

Results:结果:

Group.团体。 Amt金额

INCOME 379200收入 379200

EXPENSE 65700费用 65700

Expected Results:预期成绩:

Group.团体。 Amt金额

INCOME 379200收入 379200

EXPENSE 65700费用 65700

PROFIT 313500利润 313500

Use ROLLUP for adding an extra row and use CASE statement inside SUM() function for treating expense value as negative for calculation使用 ROLLUP 添加额外的行并在 SUM() function 中使用 CASE 语句将费用值视为负数进行计算

--MySQL
SELECT COALESCE(acc_type, 'Profit') "Group"
     , ABS(SUM(CASE WHEN acc_type = 'EXPENSE' THEN -amount ELSE amount END)) amt
FROM test
GROUP BY acc_type WITH ROLLUP

Another way by using UNION ALL使用 UNION ALL 的另一种方法

SELECT acc_type "Group"
     , SUM(amount) Amt
FROM test
GROUP BY acc_type

UNION ALL

SELECT 'Profit' AS "Group"
     , SUM(CASE WHEN acc_type = 'EXPENSE' THEN -amount ELSE amount END) Amt
FROM test

Please check this url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=f859036ffcb3d808330bce5346daee1e请检查这个 url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=f859036ffcb3d808330bce5346daee1e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM