我在这里的第一篇文章,希望我遵循正确的发布指南。如果不是,请指出。
我的带有一些示例数据的表结构(credit_notes)如下所示:
index | customer_id | user_id | doc_number | doc_date | amount | scheme_description
+-----+-------------+---------+------------+------------+--------+-------------------
1 | 8 | 2 | IABCD001 | 2012-09-08 | 1232 | XYZ Scheme
2 | 8 | 2 | IABCD001 | 2012-09-08 | 2032 | XYZ Scheme
3 | 8 | 2 | IABCD002 | 2012-09-09 | 2556 | XYZ Scheme
4 | 8 | 2 | IABCD003 | 2012-09-08 | 232 | XYZ Scheme
5 | 8 | 2 | IABCD001 | 2012-09-10 | 2556 | ABC Scheme
6 | 8 | 2 | IABCD003 | 2012-09-10 | 232 | ABC Scheme
我的要求是通过分组提取每个 scheme_description 和 doc_date 组合的总金额。这是我当前的查询:
SELECT
SUM( `amount` ) AS `totalamount`,
GROUP_CONCAT( CONCAT( `amount` , ";" ) ORDER BY `index` DESC SEPARATOR '' ) AS `amounts`,
GROUP_CONCAT( CONCAT( `doc_number` , ";" ) ORDER BY `doc_number` DESC SEPARATOR '' ) AS `docno` ,
`doc_date` AS `docdate` ,
`scheme_description` AS `schemedesc`
FROM (
SELECT
`c`.`index` ,
`c`.`doc_number` ,
`c`.`doc_date` ,
`c`.`amount` ,
`c`.`scheme_description`
FROM `credit_notes` AS `c`
WHERE `c`.`customer_id` = 8
AND `c`.`user_id` LIKE 2
)t
GROUP BY `scheme_description` , `doc_date`
此查询返回此结构:
totalamount | amounts | docno | docdate | schemedesc
+-----------+----------------+-----------------------------+------------+-----------
3496 | 1232;2032;232; | IABCD001;IABCD001;IABCD003; | 2012-09-08 | XYZ Scheme
2556 | 2556; | IABCD002; | 2012-09-09 | XYZ Scheme
23477 | 255;23222; | IABCD007;IABCD007; | 2012-09-10 | ABC Scheme
但是,我需要对此稍作改动,我想对每个不同docno的数量列求和,并按正确的顺序对其进行分组。因此,根据上述数据,查询应产生:
totalamount | amounts | docno | docdate | schemedesc
+-----------+----------------+-----------------------------+------------+-----------
3496 | 3264;232; | IABCD001;IABCD003; | 2012-09-08 | XYZ Scheme
2556 | 2556; | IABCD002; | 2012-09-09 | XYZ Scheme
23477 | 23477; | IABCD007; | 2012-09-10 | ABC Scheme
这可能使用 group_concat 和 distinct 和 sum。阅读我能找到的所有内容,但找不到任何指向正确方向的内容。
这可能吗?