0
餘額未示出適當的值如何計算總分類賬中的信用額,借項和餘額?
MySQL數據庫表:
CREATE TABLE `transactions` (
`trx_id` int(11) NOT NULL AUTO_INCREMENT,
`trx_type` enum('debit','credit') DEFAULT NULL,
`trx_amount` float DEFAULT NULL,
`trx_description` mediumtext NOT NULL,
`trx_date` date NOT NULL,
`purpose_id` int(11) NOT NULL,
`staff_id` int(11) DEFAULT NULL,
`admin_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`trx_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
/*該表數據transactions
*/
insert into `transactions`(`trx_id`,`trx_type`,`trx_amount`,`trx_description`,`trx_date`,`purpose_id`,`staff_id`,`admin_id`,`created_at`,`updated_at`)
values (1,'credit',100,'annual tour','2016-01-01',2,7,2,'2016-11-24 10:28:35','2016-11-29 12:21:08'),
(2,'debit',200,'Product Sale','2016-11-19',6,5,2,'2016-11-24 10:33:02','2016-11-29 12:21:12'),
(3,'debit',250,'Product Sale','2016-11-19',6,4,2,'2016-11-24 10:33:11','2016-11-29 12:21:43'),
(4,'credit',300,'Product Sale','2015-01-27',6,4,2,'2016-11-24 10:33:14','2016-11-29 12:21:53'),
(5,'credit',450,'Product Sale','2016-01-29',5,2,2,'2016-11-24 10:33:17','2016-11-29 12:21:58'),
(6,'debit',210,'Product Sale','2016-11-19',6,4,2,'2016-11-24 10:33:20','2016-11-29 12:22:17'),
(7,'credit',350,'Internal','2016-11-30',14,3,1,'2016-11-24 13:04:04','2016-11-29 12:22:28');
MySQL查詢:
SELECT trx_id,staff_id
, SUM(COALESCE(CASE WHEN trx_type = 'debit' THEN trx_amount END,0)) total_debits
, SUM(COALESCE(CASE WHEN trx_type = 'credit' THEN trx_amount END,0)) total_credits
, SUM(COALESCE(CASE WHEN trx_type = 'debit' THEN trx_amount END,0))
- SUM(COALESCE(CASE WHEN trx_type = 'credit' THEN trx_amount END,0)) balance
FROM erp_transactions GROUP BY staff_id HAVING balance <> 0 ORDER BY trx_id;
輸出結果:
請告訴我錯了,你想要什麼? –
你會說明你到底想要做什麼嗎? –
您的意思是無效的借記和貸記值顯示爲邏輯上它不應該在前2行中爲負值? –