我有一张桌子:

    CREATE TABLE `t` (
        `customer` VARCHAR(50) NULL DEFAULT NULL,
        `item` VARCHAR(50) NULL DEFAULT NULL,
        `debit` DECIMAL(10,2) NULL DEFAULT NULL,
        `credit` DECIMAL(10,2) NULL DEFAULT NULL,
        INDEX `customer` (`customer`),
        INDEX `item` (`item`));
INSERT INTO `t` (`customer`, `item`, `debit`, `credit`) VALUES ('cust1', 'item1', 10.00, NULL);
INSERT INTO `t` (`customer`, `item`, `debit`, `credit`) VALUES ('cust2', 'item2', NULL, 10.00);
INSERT INTO `t` (`customer`, `item`, `debit`, `credit`) VALUES ('cust3', 'item2', 20.00, NULL);
INSERT INTO `t` (`customer`, `item`, `debit`, `credit`) VALUES ('cust4', 'item3', NULL, 50.00);
INSERT INTO `t` (`customer`, `item`, `debit`, `credit`) VALUES ('cust5', 'item1', 30.00, NULL);
INSERT INTO `t` (`customer`, `item`, `debit`, `credit`) VALUES ('cust6', 'item3', NULL, 40.00);

我需要计算每个项目的客户数量,并对每个项目的借方和贷方列求和,使其看起来像这样
使用查询:
SELECT item, count(*) as num_of_custs, SUM(debit) AS debit, SUM(credit) AS credit
FROM t
GROUP BY item

但我需要把20和10(在第二排)分成两排。换言之,每一行必须有借方或贷方值,但不能两者都有。
谢谢你的帮助!

最佳答案

您的数据没有同一行的借方和贷方,因此您可以使用一个group by

SELECT item, count(*) as num_of_custs, SUM(debit) AS debit, SUM(credit) AS credit
FROM t
GROUP BY item, (case when debit is null then 1 else 0 end);

10-07 15:38