I have a simple table (ID, Member_ID, payment, date, payment_serial, running_total); I need the payment_serial to use the data for export to another system.
The export I need is all the payments made by a member (showing payment & date), sorted in order of the payment_serial and in a single row.
This was the first query I used:
SELECT
`Member_ID`,
IF(`payment_serial`=1,`payment`,0) AS `p1`,
IF(`payment_serial`=1,`date`,0) AS `p1_date`,
IF(`payment_serial`=1,`ID`,0) AS `p1_ID`,
IF(`payment_serial`=2,`payment`,0) AS `p2`,
IF(`payment_serial`=2,`date`,0) AS `p2_date`
IF(`payment_serial`=2,`ID`,0) AS `p2_ID`,
FROM monthlies
WHERE `Member_ID` = 4198739
If I use this query, I see the payments I need, but each on a separate row (which creates big import problems at the next stage):
Member_ID p1 p1_date p1_ID p2 p2_date p2_ID ...
4198739 34.50 41143 214 0 0 0 ...
4198739 0 0 0 34.50 41176 583 ...
I added GROUP BY:
SELECT
IF(`payment_serial`=1,`payment`,0) AS `p1`,
IF(`payment_serial`=1,`date`,0) AS `p1_date`,
IF(`payment_serial`=1,`ID`,0) AS `p1_ID`,
IF(`payment_serial`=2,`payment`,0) AS `p2`,
IF(`payment_serial`=2,`date`,0) AS `p2_date`,
IF(`payment_serial`=2,`ID`,0) AS `p2_ID`
FROM monthlies
WHERE `Member_ID` = 4198739
GROUP BY `Member_ID`
This gives me a single row for each member – but not each payment:
Member_ID p1 p1_date p1_ID p2 p2_date p2_ID ...
4198739 34.50 41143 214 0 0 0 ...
Where am I going wrong?
It’s not entirely your fault. MySQL implements GROUP BY wrong. Any other SQL platform would give you a syntax error at this point.
Try