mysql - SQL查询问题

标签 mysql sql

我有一个以下形式的表格:

Id, Amount(int), Date, PayType(text), Channel(text), Period(int from 1 to 5)

基本上一个人可以使用不同的 channel 和不同的支付类型进行多次支付。

我想要的是联系人在每个时期给出的 channel 、付款类型和总金额,对于首次通过 channel “TE”给出的联系人(但稍后可能通过其他 channel 给出)。

所以结果应该是:

Id, Amount_Period1, PayType_Period1, Channel_Period1, Amount_Period2, PayType_Period2, PayType_Period2... etc until period5...

我不知道如何执行此查询,或者想出一种更简单的方法来查看最初使用 channel “TE”的人是否继续使用它或使用不同的 channel ......

基本上,我正在尝试建立所使用 channel 的历史记录。

例如, 联系人 1 的第一笔付款是通过 channel “TE”完成的,金额 65,付款类型:“VI”,在第 3 期...他的第二笔付款是在第 5 期通过 channel “WW”完成的,金额 30,付款类型:“CH”等。 ..

链接到示例 sql 文件:Sample

最佳答案

也许是这样的:

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 语句填充适当的值。但是,如果您在同一付款类型/ channel 中有多个记录,那么您可能需要对所有不同 channel 和付款类型的金额进行求和并进行分组。

但正如 Gordan 所说...如果在给定时间段内相同付费类型和 channel 存在多个 ID,那么您可能需要进行一些聚合...

关于mysql - SQL查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115360/

相关文章:

python - 存储海量数据;数据库、XML 还是纯文本?

mysql - 从 3 个表中选择具有相同列 id 的记录

mysql - 在尝试删除 MySQL 中的任何这些记录之前,如何检查记录列表的外键引用?

mysql - 使用分组依据选择倒数第二个日期

php - 如何将新版本的 phpmyadmin 安装到服务器上?

mysql - 从 SQL 查询中获取一列中的多个值

mysql - 根据表A中的数组值从表B中选择多行

mysql - 查询与另一个表中的条数相等的记录

sql - 仅当 Entity Framework 映射列存在时

MySQL 未在 XAMPP 中启动