有一个GROUP_CONCAT,有一个GROUP_SUM吗?

时间:2018-07-01 19:16:01

标签: mysql sql select

qty 是一个整数。此SQL可以工作,但是我想对 qty 值求和,而不是将它们连接在一起。没有GROUP_SUM:还有其他名称吗?

SELECT sku as filterSKU, storenumber as storenumberSKU,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 0 THEN qty ELSE NULL END)) AS Monday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 1 THEN qty ELSE NULL END)) AS Tuesday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 2 THEN qty ELSE NULL END)) AS Wednesday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 3 THEN qty ELSE NULL END)) AS Thursday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 4 THEN qty ELSE NULL END)) AS Friday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 5 THEN qty ELSE NULL END)) AS Saturday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 6 THEN qty ELSE NULL END)) AS Sunday
    FROM `reconciled`.sale 
    GROUP BY sku, storenumber;

这是桌子:

CREATE TABLE `sale` (
  `saleID` int(11) NOT NULL AUTO_INCREMENT,
  `EmployeeFirstName` varchar(45) DEFAULT NULL,
  `EmployeeLastName` varchar(45) DEFAULT NULL,
  `ProductDescription` varchar(45) DEFAULT NULL,
  `Unit` varchar(45) DEFAULT NULL,
  `SKU` varchar(45) DEFAULT NULL,
  `Qty` int(11) DEFAULT NULL,
  `UnitCost` decimal(10,3) DEFAULT NULL,
  `UnitPrice` decimal(10,3) DEFAULT NULL,
  `Manufacturer` varchar(45) DEFAULT NULL,
  `EmployeeNumber` varchar(45) DEFAULT NULL COMMENT 'The employee who handled the transaction',
  `LoyaltyNumber` varchar(45) DEFAULT NULL,
  `StoreNumber` varchar(45) DEFAULT NULL,
  `DateOfTransaction` date DEFAULT NULL,
  `TimeOfTransaction` time DEFAULT NULL,
  `DateOfTransactionString` varchar(45) DEFAULT NULL,
  `TimeOfTransactionString` varchar(45) DEFAULT NULL,
  `WeekdayOfTransaction` int(11) DEFAULT NULL,
  `MonthOfTransaction` int(11) DEFAULT NULL,
  `YearOfTransaction` int(11) DEFAULT NULL,
  `WeekdayNameOfTransaction` varchar(45) DEFAULT NULL,
  `MonthNameOfTransaction` varchar(45) DEFAULT NULL,
  `TotalPrice` decimal(10,3) DEFAULT NULL,
  PRIMARY KEY (`saleID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:6)

它简称为sum。您可以通过group by子句(您已经拥有!)来实现分组:

SELECT   sku AS filterSKU, storenumber AS storenumberSKU,
         SUM(CASE weekdayoftransaction WHEN 0 THEN qty ELSE NULL END) AS Monday,
         SUM(CASE weekdayoftransaction WHEN 1 THEN qty ELSE NULL END) AS Tuesday,
         SUM(CASE weekdayoftransaction WHEN 2 THEN qty ELSE NULL END) AS Wednesday,
         SUM(CASE weekdayoftransaction WHEN 3 THEN qty ELSE NULL END) AS Thursday,
         SUM(CASE weekdayoftransaction WHEN 4 THEN qty ELSE NULL END) AS Friday,
         SUM(CASE weekdayoftransaction WHEN 5 THEN qty ELSE NULL END) AS Saturday,
         SUM(CASE weekdayoftransaction WHEN 6 THEN qty ELSE NULL END) AS Sunday
FROM     `reconciled`.sale 
GROUP BY sku, storenumber;