MySQL GROUP BY扩展

时间:2014-02-14 01:59:27

标签: 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` (`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);

我需要计算每件商品的客户数量,并将每件商品的借方和贷记列相加,以便它看起来像这样

screenshot

使用查询:

SELECT item, count(*) as num_of_custs, SUM(debit) AS debit, SUM(credit) AS credit
FROM t
GROUP BY item

但我需要将20和10(第二行)分成两行。换句话说,每一行必须有借方或贷方价值,但不能同时具有两者。

我感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

您的数据在同一行没有借记和点数,因此您可以使用一个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);