1

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
4

1 回答 1

0

也许像这样

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

基本上按现在的方式返回数据,但使用计数,然后在重复数量的管道上连接以使其最多 5 组

于 2013-07-08T08:32:09.337 回答