根据另一列的重复(相同)条目对一列进行计数

时间:2019-02-05 10:44:23

标签: sql oracle

我想根据最近通话和通话组的周数创建最近通话记录。

实际数据如下所示,其中包含通话ID,通话日期和通话分组

callid |  Date   |   Group
----------------------------
1      | 6-1-18  |    a1
2      | 6-1-18  |    a2
3      | 7-1-18  |    a3
4      | 8-1-18  |    a1
5      | 9-1-18  |    a2
6      | 9-1-18  |    a4

预期数据将显示每个呼叫组的呼叫数量,该数量对应于上次呼叫以来的星期数

week   |     |
from   |     |
last   |Group|Group
call   |  a1 |  a2
--------------------
1      | 2   |  2 ->number of calls
2      | -   |  - 
3      | 1   |  - 
4      | 2   |  - 
5      | -   |  3  
6      | -   |  -  

有人可以告诉我一些解决方法

1 个答案:

答案 0 :(得分:1)

尽管您提供的数据集很小,并且不足以覆盖所有情况,但这里有一条sql可以计算每个呼叫与组中最后一个呼叫之间的周差,并计算每个呼叫的呼叫数特定星期差异的组。

with your_table as (
select 1 as "callid", to_date('6-1-18','dd-mm-rr') as "date", 'a1' as "group" from dual
union select 2, to_date('6-1-18','mm-dd-rr'), 'a2' from dual
union select 3, to_date('7-1-18','mm-dd-rr'), 'a3' from dual
union select 4, to_date('8-1-18','mm-dd-rr'), 'a1' from dual
union select 5, to_date('9-1-18','mm-dd-rr'), 'a2' from dual
union select 6, to_date('6-1-18','mm-dd-rr'), 'a4' from dual
),
 data1 as (
select t.*, max(t."date") over (partition by t."group") last_call_dt from your_table t
),
data2 as (select  t.*, round((last_call_dt-t."date")/7,0) as weeks_diff from data1 t)
select * from (
select t.weeks_diff, t."callid", t."group" from data2 t
)
PIVOT
(
  COUNT("callid")
  FOR "group" IN ('a1', 'a2', 'a3','a4')
)
order by weeks_diff

要在您的桌子上尝试一下,只需进行以下更改:

使用your_table作为(从my_table中选择*),....

让我知道这是怎么回事:)