如何用多次出现的模式填充 varchar
Posted
技术标签:
【中文标题】如何用多次出现的模式填充 varchar【英文标题】:How to fill a varchar with a number of occurences of a pattern 【发布时间】:2013-07-05 11:24:21 【问题描述】:我使用 GROUP_CONCAT 在一行中检索每个玩家的前五笔交易数据,但由于我的最终目标是以 csv 格式导出这些数据,因此我希望最后有一个确切数量的列。如何连接特定数量的模式出现以始终获得 5 列?在我的情况下,我需要 5 列用于金额,5 列用于发行日期,依此类推。
这是原始查询:
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 2500|1000|1000|1000 2011-07-18|2011-09-19|2011-09-19|2011-09-19 38.5694|95.8188 146 1000 2011-02-27 187 1000|1000 2010-09-15|2011-01-19 感谢您的帮助 【参考方案1】:可能是这样
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 组
【讨论】:
以上是关于如何用多次出现的模式填充 varchar的主要内容,如果未能解决你的问题,请参考以下文章