我想将季度产品销售结果分成 4 列(每个季度一个)。我的表如下:
CREATE TABLE `tcustomerscontracts` (
`contract_id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL DEFAULT '0',
`contract_quantity` decimal(8,2) NOT NULL DEFAULT '0.00',
`contract_date_from` varchar(10) NOT NULL,
`customer_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`contract_id`),
KEY `PRODUCT` (`product_id`),
KEY `CUSTOMER` (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
应用以下查询:
SELECT `tcustomerscontracts`.`contract_id`, YEAR(`tcustomerscontracts`.`contract_date_from`) AS forecast_year,`tproducts`.`product_id`,`tproducts`.`product_name`,SUM(contract_quantity) AS forecast_quantity,QUARTER(`tcustomerscontracts`.`contract_date_from`) AS forecast_quarter FROM `tcustomerscontracts`
INNER JOIN `tproducts` ON `tproducts`.`product_id` = `tcustomerscontracts`.`product_id`
GROUP BY YEAR(`tcustomerscontracts`.`contract_date_from`),`tproducts`.`product_name`,QUARTER(`tcustomerscontracts`.`contract_date_from`)
ORDER BY YEAR(`tcustomerscontracts`.`contract_date_from`) DESC, `tproducts`.`product_name` ASC, QUARTER(`tcustomerscontracts`.`contract_date_from`) ASC;
提前致谢
感谢@P.Salmon,我尝试使用所指出的建议,我相信我走在正确的道路上,即使它仍然不完整。
我的新查询是:
SELECT
YEAR(`contract_date_from`) as YEAR,product_id AS PROD_ID,
CASE WHEN (quarter(contract_date_from)=1) THEN SUM(contract_quantity) ELSE 0 END AS Q1,
CASE WHEN (quarter(contract_date_from)=2) THEN SUM(contract_quantity) ELSE 0 END AS Q2,
CASE WHEN (quarter(contract_date_from)=3) THEN SUM(contract_quantity) ELSE 0 END AS Q3,
CASE WHEN (quarter(contract_date_from)=4) THEN SUM(contract_quantity) ELSE 0 END AS Q4
FROM tcustomerscontracts
where customer_id=2
GROUP BY YEAR(`contract_date_from`) DESC, `product_id` ASC,QUARTER(`tcustomerscontracts`.`contract_date_from`) ASC;
结果如下:
结果应如红色箭头所示。相反,在从一个季度到另一个季度的过渡中会创建一个新行。