MySQL分组扩展

MySQL分组扩展,mysql,sql,Mysql,Sql,我有一张桌子: 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`

我有一张桌子:

    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(在第二行)分成两行。换句话说,每行必须有借方或贷方值,但不能同时有借方和贷方值


我感谢你的帮助

您的数据在同一行上没有借方和贷方,因此您可以通过一个
分组来实现这一点:

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);