目标是分析不同细分市场随着时间的变化情况。因此,有一部分客户是在2017年第三季度获得的,他们在该季度花费了特定金额的资金)。我想知道他们从2017-10年度开始的所有其他月份花费了多少。
我有一个查询,该查询返回的结果在某些情况下是重复的。因此,例如,如果一个客户总共只有2笔购买交易(2017年第三季度为1次,2018年第一季度为1次),则查询返回的是他在2018年第一季度花费的确切金额。但是,如果某个客户在2017年第3季度进行了2次购买,则该查询返回的结果与实际销售信息相比是重复的。在一个季度中有更多购买的客户,查询返回的结果没有任何意义(下图)。
select left(iip1.created_at, 7), sum(iip1.revenue_usd)
from invoice_item_pay iip1
LEFT JOIN invoice_item_pay eiip2
ON iip1.client_id = iip2.client_id
WHERE iip1.created_at BETWEEN '2017-10-01 00:00:00' AND '2019-04-31 23:59:59'
AND iip2.created_at BETWEEN '2017-07-01 00:00:00' AND '2017-09-30 23:59:59'
AND iip.client_id = 'clientid001'
GROUP BY left(eiip.created_at, 7)
实际和预期结果如下所示。请在排序此查询时获得一些帮助。
示例数据和预期结果的屏幕截图-https://imgur.com/a/r7XbxT2
样本数据表-
<table>
<tbody>
<tr>
<td class="xl65" style="height: 16.0pt; width: 95pt;" width="127" height="21">client_id</td>
<td class="xl65" style="height: 16.0pt; width: 177pt;" width="236" height="21">product</td>
<td class="xl65" style="border-left: none; width: 133pt;" width="177">revenue_usd</td>
<td class="xl65" style="border-left: none; width: 95pt;" width="127">created_at</td>
</tr>
<tr>
<td class="xl65" style="height: 16.0pt; width: 95pt;" width="127" height="21">clientid001</td>
<td class="xl65" style="height: 16.0pt; width: 177pt;" width="236" height="21">product_id_6</td>
<td class="xl65" style="border-left: none; width: 133pt;" width="177">9.99</td>
<td class="xl65" style="border-left: none; width: 95pt;" width="127">2018-03-25</td>
</tr>
<tr>
<td class="xl65" style="height: 16.0pt; width: 95pt;" width="127" height="21">clientid001</td>
<td class="xl65" style="height: 16.0pt; width: 177pt;" width="236" height="21">product_id_7</td>
<td class="xl65" style="border-left: none; width: 133pt;" width="177">9.99</td>
<td class="xl65" style="border-left: none; width: 95pt;" width="127">2018-03-25</td>
</tr>
<tr>
<td class="xl65" style="height: 16.0pt; width: 95pt;" width="127" height="21">clientid001</td>
<td class="xl65" style="height: 16.0pt; width: 177pt;" width="236" height="21">product_id_15</td>
<td class="xl65" style="border-left: none; width: 133pt;" width="177">65.95 </td>
<td class="xl65" style="border-left: none; width: 95pt;" width="127">2019-04-11</td>
</tr>
</tbody>
</table>
预期结果-
<table>
<tbody>
<tr>
<td class="xl65" style="height: 16.0pt; width: 95pt;" width="127" height="21">created_at</td>
<td class="xl65" style="height: 16.0pt; width: 177pt;" width="236" height="21">revenue_usd</td>
</tr>
<tr>
<td class="xl65" style="height: 16.0pt; width: 95pt;" width="127" height="21">2018-03</td>
<td class="xl65" style="height: 16.0pt; width: 177pt;" width="236" height="21">19.98</td>
</tr>
<tr>
<td class="xl65" style="height: 16.0pt; width: 95pt;" width="127" height="21">2019-04</td>
<td class="xl65" style="height: 16.0pt; width: 177pt;" width="236" height="21">65.95</td>
</tr>
</tbody>
</table>