【发布时间】:2019-08-07 03:03:20
【问题描述】:
我正在使用支持许多 VB6 客户端的 MySQL 5.0 服务器。需要创建一个非常简单的应用程序来输出几个关键表的总数。无论如何,我都不是 SQL 专家,但我似乎遇到了各种错误。
目标是创建一个临时表,其中包含来自数据库中各种表的聚合。每行需要一个Total 列(在右侧),每列需要在底部行总计。
期望的输出:
Account Debit Credit Total
1 350 1000.94 0 -1000.94
2 103 0 551.34 551.34
3 356 0 10200.41 10200.41
...
14 000 1000.94 10751.75 9750.81
当前 MySQL SQL 适用于总计行,但无法弄清楚如何创建总计行(上面的#14):
SET @PCName := "REPORTS";
Create temporary table TempTable( Account int, Debit int, Credit int, Total int);
(
SELECT * FROM (
SELECT 1 as seq, '350' as Account, COALESCE(SUM(invoice_amount),0) as Debit, 0 as Credit, COALESCE(SUM(invoice_amount),0) * -1 as Total FROM invoice WHERE Voided = 0
Union all
SELECT 2 as seq, '103' as Account, 0 as Debit, COALESCE(SUM(check_amount),0) as Credit, COALESCE(SUM(check_amount),0) as Total FROM auctiondbh.Checks
Union all
SELECT 3 as seq, '356' as Account, 0 as Debit, COALESCE(SUM(Amount),0) as Credit, COALESCE(SUM(Amount),0) as Total FROM ScratchBal WHERE rec_Owner = @PCName AND RowType = 'BFC'
Union all
SELECT 4 as seq, '554' as Account, 0 as Debit, COALESCE(SUM(Amount),0) as Credit, COALESCE(SUM(Amount),0) as Total FROM ScratchBal WHERE rec_Owner = @PCName AND RowType = 'FEED' AND Description = 'Total Feed'
Union all
SELECT 5 as seq, '505' as Account, 0 as Debit, COALESCE(SUM(Amount),0) as Credit, COALESCE(SUM(Amount),0) as Total FROM ScratchBal WHERE rec_Owner = @PCName AND RowType = 'TOT_COMM'
Union all
SELECT 6 as seq, '525' as Account, 0 as Debit, COALESCE(SUM(Amount),0) as Credit, COALESCE(SUM(Amount),0) as Total FROM ScratchBal WHERE rec_Owner = @PCName AND RowType = 'CUSTOM_CHARGES' AND description = 'Commingle%'
-- ONE ATTEMPT FOLLOWS:
-- union all
-- select 14 as seq, '000' as Account, (SELECT SUM(Debit)) AS Debit, (SELECT SUM(Credit)) AS Credit, ((SELECT SUM(Debit)) - (SELECT SUM(Credit))) AS Total
) x
);
-- ANOTHER ATTEMPT FOLLOWS:
-- select * FROM TempTable
-- union all
-- select 14 as seq, '000' as Account, (SELECT SUM(debit)) AS Debit, (SELECT SUM(credit)) AS Credit, ((SELECT SUM(debit)) - (SELECT SUM(credit))) AS Total from TempTable
如何修复此 SQL 以创建包含借方、贷方和总计列总计的第 14 行?
【问题讨论】:
标签: mysql