Mysql 查询中的SQL问题

Mysql 查询中的SQL问题,mysql,sql,Mysql,Sql,我有以下表格: Id, Amount(int), Date, PayType(text), Channel(text), Period(int from 1 to 5) 基本上,一个人可以使用不同的渠道和不同的支付类型支付多次 我想要的是每个时期联系人提供的渠道、付款类型和总金额,对于第一次通过渠道“TE”提供的联系人(但以后可能通过其他渠道提供) 因此,结果应该是: Id, Amount_Period1, PayType_Period1, Channel_Period1, Amount_Pe

我有以下表格:

Id, Amount(int), Date, PayType(text), Channel(text), Period(int from 1 to 5)
基本上,一个人可以使用不同的渠道和不同的支付类型支付多次

我想要的是每个时期联系人提供的渠道、付款类型和总金额,对于第一次通过渠道“TE”提供的联系人(但以后可能通过其他渠道提供)

因此,结果应该是:

Id, Amount_Period1, PayType_Period1, Channel_Period1, Amount_Period2, PayType_Period2, PayType_Period2... etc until period5...
我不知道该怎么做这个查询,或者想一个更简单的方法来看看最初使用“TE”频道的人是继续使用它还是使用不同的频道

基本上,我试图建立一个历史的渠道使用

比如说,, 联系人1第一次付款由频道“TE”完成,金额65,付款类型:“VI”,在第3期。。。他在第5期通过“WW”频道第二次付款,金额30,付款类型:“CH”等


链接到示例sql文件:

可能类似于:

Select ID, 
case when P1.period=1 then P1.Amount end as Amount_Period1,
case when P1.period=1 then P1.PayType end as PayType_Period1,
case when P1.period=1 then P1.Channel end as Channel_Period1,
case when P2.period=2 then P2.Amount end as Amount_Period2,
case when P2.period=2 then P2.PayType end as PayType_Period2,
case when P2.period=2 then P2.Channel end as Channel_Period2,
case when P3.period=3 then P3.Amount end as Amount_Period3,
case when P3.period=3 then P3.PayType end as PayType_Period3,
case when P3.period=3 then P3.Channel end as Channel_Period3,
case when P4.period=4 then P4.Amount end as Amount_Period4,
case when P4.period=4 then P4.PayType end as PayType_Period4,
case when P4.period=4 then P4.Channel end as Channel_Period4,
case when P5.period=5 then P5.Amount end as Amount_Period5,
case when P5.period=5 then P5.PayType end as PayType_Period5,
case when P5.period=5 then P5.Channel end as Channel_Period5
From Table P1
LEFT JOIN Table P2
 on P1.ID = P2.ID and P1.Period = 1 and P2.Period=2
LEFT JOIN table P3
 on P2.ID = P3.ID and P2.Period = 2 and P3.Period=3
LEFT JOIN table P4
 on P3.ID = P4.ID and P3.Period = 3 and P4.Period=4
LEFT JOIN table P5
 on P4.ID = P5.ID and P4.Period = 4 and P5.Period=5
这样做的目的是5次自连接,以获取同一“行”上的所有记录,并使用case语句填充适当的值。但是,如果您在同一付款类型/渠道中有多个记录,则您可能希望按所有不同的渠道和付款类型对金额和组进行合计


但正如戈尔丹所说。。。如果同一付款类型和渠道在给定时间段内存在多个ID,则您可能需要进行一些聚合…

在这一点上,我认为最符合逻辑的是:

SELECT Id, Channel, PayType, Period, sum(amount)
FROM unknown_table
GROUP by Id, PayType, Channel, Period
ORDER BY Id, Period, Date; -- for example

(您可以使用来共享您的样本)

样本数据和期望的结果确实有助于解释您想要什么。例如,如果某人在给定的时间段内有多条记录,该怎么办?我编辑了我的帖子,并将链接添加到示例sql文件中!顺便说一句,你的链接对我不起作用。@GordonLinoff&Greg添加了新链接(link1)应该有效吗?@Mickeel_Paris你也应该避免数据的外部链接。在这里阅读如何正确地执行此操作:一个问题是它们都来自同一个表“act”,句点是列中的一个,这就是5个自联接的原因。数据在每个派生表/内联视图中按句点进行解析。Hmm。。看看你的评论。。似乎付款可以在随机周期2,5发生,一个ID为1,3,5,另一个ID为2,4。对吗?如果是这样的话,我知道为什么这只在“某种程度上”起作用,如果在第1期没有付款,那么这不起作用。