我有一个表格,格式如下:
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,PaymentType:"VI",在第3期...他在第5期的第二次付款是通过渠道"WW",金额30,PaymentType:"CH“等。
指向示例sql文件的链接:Sample
发布于 2016-03-21 01:29:35
可能是这样的:
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,那么您可能需要进行一些聚合...
发布于 2016-03-21 07:27:12
在这一点上,对我来说最合乎逻辑的应该是这样:
SELECT Id, Channel, PayType, Period, sum(amount)
FROM unknown_table
GROUP by Id, PayType, Channel, Period
ORDER BY Id, Period, Date; -- for example(您可以使用http://sqlfiddle.com/共享您的样本)
https://stackoverflow.com/questions/36115360
复制相似问题