2013-07-08 53 views
1

我使用GROUP_CONCAT檢索每個球員的前五個交易數據,但是由於我的最終目標是以csv格式導出此數據,因此我希望獲得確切數量的最後列。如何連接特定數量的模式出現總是獲得5列?在我的情況下,我需要5列的金額,5的發行日期,等等。如何填充一個具有多個模式的varchar

這裏是原始查詢:

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 
+0

你能提供一些樣本數據? – golimar

+0

您的意思是我們使用當前查詢獲得的結果嗎?當然,結果如下: 4 2500 | 1000 | 1000 | 1000 2011-07-18 | 2011-09-19 | 2011-09-19 | 2011-09-19 38.5694 | 95.8188 2011 -02-27 1000 | 1000 \t 2010-09-15 | 2011-01-19 感謝您的幫助 – mordekhai

回答

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組

+0

令人驚歎。非常感謝 ! – mordekhai