如何使用where子句获取mysql sum多列?

时间:2017-10-29 17:20:20

标签: mysql sql

我有一张像这样的桌子。我想得到 总和CREATE TABLE `tbl_test` ( `id` int(8) NOT NULL, `amount` decimal(8,2) NOT NULL, `status` enum('paid','unpaid') COLLATE utf8_unicode_ci DEFAULT NULL, `inserted` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; INSERT INTO `tbl_test` (`id`, `amount`, `status`, `inserted`, `updated`) VALUES (1, '2510.00', 'unpaid', '2017-10-29 17:06:11', NULL), (2, '1120.00', 'paid', '2017-10-29 17:06:11', NULL), (3, '110.00', 'unpaid', '2017-10-29 17:06:43', NULL), (4, '920.00', 'paid', '2017-10-29 17:06:43', NULL), (5, '1098.00', 'paid', '2017-10-29 17:07:31', NULL), (6, '9990.00', 'paid', '2017-10-29 17:07:31', NULL), (7, '1198.00', 'unpaid', '2017-10-29 17:07:31', NULL), (8, '140.00', 'unpaid', '2017-10-29 17:07:31', NULL); ALTER TABLE `tbl_test` ADD PRIMARY KEY (`id`); ALTER TABLE `tbl_test` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;COMMIT; 付款总额select 未付的金额 在一个查询中。

这是否可以通过三列获得单个查询中的所有总和 输出应该是

enter image description here

option

1 个答案:

答案 0 :(得分:4)

您可以使用条件聚合:

SELECT SUM(amount)  AS TotalAmount
     , SUM(CASE WHEN status='paid' THEN amount END) AS PaidAmount
     , SUM(CASE WHEN status='unpaid' THEN amount END) AS UnpaidAmount
FROM `tbl_test`;

<强> Rextester Demo