Search code examples
mysqlsqlcsvvarchargroup-concat

How to fill a varchar with a number of occurences of a pattern


I retrieve each player's first five transactions data on one line with GROUP_CONCAT but since my final goal is to export this data in csv format I want to have an exact number of columns at the end. How to concat a specific number of occurences of a pattern to always obtain 5 columns ? In my case I need 5 columns for the amounts, 5 for the issue dates, and so on.

Here is the original query :

SELECT
p.id,  
GROUP_CONCAT(t1.amount SEPARATOR "|") as amounts,  
GROUP_CONCAT(t1.issueDate SEPARATOR "|") as issueDates,   
GROUP_CONCAT((select t2.amountInEuro*100/t1.amountInEuro from Transaction t2 where t2.type = 3 and t2.id = t1.deposit_id) SEPARATOR "|") as bonusAmounts 
FROM Transaction t1 join Player p on p.id = t1.player_id 
WHERE   
t1.type = 0 and   
t1.status = 0 and   
exists (select 1 from Transaction tr where tr.issueDate between '2010-07-03 00:00:00' and '2013-07-03 23:59:59' and tr.player_id = t1.player_id) 
GROUP BY t1.player_id 
HAVING count(*) <= 5

Solution

  • Maybe like this

    SELECT id,
        CONCAT(amounts, REPEAT('|', 5 - GroupCount)) AS amounts,
        CONCAT(issueDates, REPEAT('|', 5 - GroupCount)) AS issueDates,
        CONCAT(bonusAmounts, REPEAT('|', 5 - GroupCount)) AS bonusAmounts
    FROM
    (
        SELECT
            p.id,  
            GROUP_CONCAT(t1.amount SEPARATOR "|") as amounts,  
            GROUP_CONCAT(t1.issueDate SEPARATOR "|") as issueDates,   
            GROUP_CONCAT(t2.amountInEuro*100/t1.amountInEuro SEPARATOR "|") as bonusAmounts,
            COUNT(*) AS GroupCount 
        FROM Transaction t1 
        JOIN Player p 
        ON p.id = t1.player_id 
        INNER JOIN (SELECT player_id, COUNT(*) FROM Transaction WHERE issueDate BETWEEN '2010-07-03 00:00:00' AND '2013-07-03 23:59:59' GROUP BY player_id) tr
        ON tr.player_id = t1.player_id
        LEFT OUTER JOIN Transaction t2
        ON t2.id = t1.deposit_id AND type = 3
        WHERE t1.type = 0 
        and t1.status = 0 
        GROUP BY t1.player_id 
        HAVING GroupCount <= 5
    ) Sub1
    

    Basically return the data as it is now, but with the count, then concatenate on a repeated number of pipes to get it up to 5 groups