我需要创建一个MariaDB SQL,它允许我将两列(借记卡和信用列)相加以获得差异,并返回每个不同帐户类型的小计。表格如下:
Account | Debit | Credit
acc1 | 1 | 2
acc1 | 1 | 4
acc2 | 3 | 2
acc2 | 2 | 1
acc2 | 2 | 1
acc3 | 5 | 2
acc3 | 5 | 1
acc3 | 5 | 2
我想返回以下内容:
Account | Balance(debit-credit)
acc1 | -1
acc1 | -3
-------------------------------
Total acc1 | -4
-------------------------------
acc2 | 1
acc2 | 1
acc2 | 1
-------------------------------
Total acc2 | 3
-------------------------------
acc3 | 3
acc3 | 4
acc3 | 3
-------------------------------
Total acc3 | 10
-------------------------------
GrandTotal | 9
-------------------------------
Grandtotal is Totals of acc1 + acc2 + acc3
这是我到目前为止所尝试过的,但是我所有的只是得到了格式而且没有小计
SELECT * FROM (
SELECT COALESCE(account,'TOTAL') AS Account, CASE
WHEN account LIKE 'INC%'
THEN sum((gl.credit - gl.debit))
ELSE sum((gl.debit - gl.credit))
END AS Balance
FROM `tabGL Entry` gl
WHERE (NOT (account LIKE 'CASS%')
AND NOT (account LIKE 'CLIA%')
AND NOT (account LIKE 'FASS%'))
GROUP BY account WITH ROLLUP
) AS gl
ORDER BY CASE
WHEN account LIKE 'INC%' THEN 1
WHEN account LIKE 'DCOI%' THEN 2
WHEN account LIKE 'DMC%' THEN 3
WHEN account LIKE 'INFC%' THEN 4
WHEN account LIKE 'IDEX%' THEN 5
ELSE 6
END
答案 0 :(得分:1)
您可以使用UNION
进行尝试,例如:
SELECT *
FROM (SELECT COALESCE('TOTAL ', account) AS Account
, SUM(CASE WHEN account LIKE 'INC%'
THEN (gl.credit - gl.debit)
ELSE (gl.debit - gl.credit)
END) AS Balance
FROM `tabGL Entry` gl
WHERE (NOT (account LIKE 'CASS%')
AND NOT (account LIKE 'CLIA%')
AND NOT (account LIKE 'FASS%'))
GROUP BY account WITH ROLLUP
-- UNION SELECT account
-- , CASE WHEN account LIKE 'INC%'
-- THEN (gl.credit - gl.debit)
-- ELSE (gl.debit - gl.credit)
-- END AS Balance
-- FROM `tabGL Entry` gl
-- WHERE (NOT (account LIKE 'CASS%')
-- AND NOT (account LIKE 'CLIA%')
-- AND NOT (account LIKE 'FASS%'))
) AS gl
ORDER BY CASE
WHEN account LIKE 'INC%' THEN 1
WHEN account LIKE 'DCOI%' THEN 2
WHEN account LIKE 'DMC%' THEN 3
WHEN account LIKE 'INFC%' THEN 4
WHEN account LIKE 'IDEX%' THEN 5
ELSE 6
END
我认为这应该做你想做的事情
注释掉的部分用于单行,上部用于小计
现在,在此处的最后一条评论之后,查询会为您提供小计和总计
COALESCE分组似乎是问题所以现在由LEFT(account,3)
完成,而ORDER
语句必须修改为3个字符
SELECT *
FROM (SELECT LEFT(account,3) AS Account
, SUM(CASE WHEN account LIKE 'INC%'
THEN (credit - debit)
ELSE (debit - credit)
END) AS Balance
FROM acc
GROUP BY LEFT(account,3) WITH ROLLUP
) AS ac
ORDER BY CASE
WHEN account LIKE 'INC%' THEN 1
WHEN account LIKE 'DCO%' THEN 2
WHEN account LIKE 'DMC%' THEN 3
WHEN account LIKE 'INF%' THEN 4
WHEN account LIKE 'IDE%' THEN 5
ELSE 6
END