Вы также можете сделать это с одним SELECT следующим образом:
SELECT invoiceId, CONCAT(
SUM(IF(vatId=7,vatAmount,0))
,if( SUM(IF(vatId=8,vatAmount,0)) >0
, CONCAT(',',SUM(IF(vatId=8,vatAmount,0)))
,'')
) AS listVatAmounts
FROM invoiceId
GROUP BY invoiceId;
ИЛИ с подзапросом и для всех invoiceIds
SELECT
invoiceId,
GROUP_CONCAT(vatAmount ORDER BY vatId SEPARATOR ', ') AS listVatAmounts
FROM (
SELECT id, invoiceId, vatId, SUM(vatAmount) as vatAmount
FROM invoiceId
GROUP BY invoiceId,vatId
) grp
GROUP BY invoiceId
ORDER BY id;
Sample
MariaDB [bernd]> SELECT invoiceId, CONCAT(
-> SUM(IF(vatId=7,vatAmount,0))
-> ,if( SUM(IF(vatId=8,vatAmount,0)) >0
-> , CONCAT(',',SUM(IF(vatId=8,vatAmount,0)))
-> ,'')
-> ) AS listVatAmounts
-> FROM invoiceId
-> GROUP BY invoiceId;
+-----------+----------------+
| invoiceId | listVatAmounts |
+-----------+----------------+
| 4 | 47.00,15.75 |
| 5 | 10.05 |
| 6 | 11.04 |
+-----------+----------------+
3 rows in set (0.01 sec)
MariaDB [bernd]>
Образец 2
MariaDB [bernd]> SELECT
-> invoiceId,
-> GROUP_CONCAT(vatAmount ORDER BY vatId SEPARATOR ', ') AS listVatAmounts
-> FROM (
-> SELECT id, invoiceId, vatId, SUM(vatAmount) as vatAmount
-> FROM invoiceId
-> GROUP BY invoiceId,vatId
-> ) grp
-> GROUP BY invoiceId
-> ORDER BY id;
+-----------+----------------+
| invoiceId | listVatAmounts |
+-----------+----------------+
| 4 | 47.00, 15.75 |
| 5 | 10.05 |
| 6 | 11.04 |
+-----------+----------------+
3 rows in set (0.00 sec)
MariaDB [bernd]>