请问一下这个输出结果,用sql server要怎么解答呢?
原数据如下:
想要的输出结果如下:
解释:
例如11月1日这天,这个用户有一个语音留言,他并没有听。11月2日,他有并且接听了一个新增的语音留言,还把昨天的语音留言也听了,所以新增加了一个语音留言,总共接听了两个语音留言。
但是计算的时候,要求11月2日的语音留言变成了2,因为要把11月1日接收的语音也加进去。
同理,11月3日用户收到了3个语音留言但是没有接听。到了11月4日,用户虽然没有收到新的留言可是把11月3日的3个留言听了,输出的表格就要变成11月4日有3个语音留言并且也接听了3个语音留言。
总之输出的结果是语音留言必须大于等于接听语音留言。
恳请大家帮忙看看如何写这段sql server 的代码。谢谢。
sql 执行结果截图
源码:
select
"日期",
"用户",
--"语音留言" ,
iif ((lag("语音留言",1,0) over (partition by "用户","日期" order by "用户","日期")+"语音留言"-"接听语音留言" >"接听语音留言"), "语音留言","接听语音留言") "LAG语音留言",
"接听语音留言"
from info order by"用户","日期" ;
SELECT
t2.create_date,
t2.liuyan_sum + IFNULL((SELECT
SUM(t1.liuyan_sum - t1.jieting_sum)
FROM
csdn_mobile t1
WHERE
t1.create_date < t2.create_date),
0),
t2.jieting_sum
FROM
csdn_test.csdn_mobile t2;
SELECT
t2.create_date,
t2.liuyan_sum + ISNULL((SELECT
SUM(t1.liuyan_sum - t1.jieting_sum)
FROM
csdn_mobile t1
WHERE
t1.create_date < t2.create_date),
0),
t2.jieting_sum
FROM
csdn_test.csdn_mobile t2;
真的非常不好意思,我套上原数据还是有 还是有出入,我可以复制粘贴一部分给你看一下吗?
日期 用户 语音留言 接听语音留言
10/1/2022 local 4 1
10/2/2022 local 3 6
10/3/2022 restauration 7 7
10/4/2022 local 6 6
10/4/2022 restauration 6 6
10/5/2022 local 1 1
10/6/2022 local 1 1
10/6/2022 restauration 3 3
10/7/2022 restauration 4 4
10/8/2022 local 0 1
10/9/2022 local 1 3
10/10/2022 local 0 1
10/11/2022 local 2 2
10/11/2022 restauration 6 6
10/12/2022 restauration 4 4
10/14/2022 restauration 1 1
10/15/2022 local 1 1
10/16/2022 local 1 1
10/17/2022 local 1 0
10/17/2022 restauration 1 1
10/18/2022 local 1 2
10/18/2022 restauration 1 1
10/19/2022 restauration 2 2
10/20/2022 restauration 4 4
select
[日期],[用户],
[语音留言总数]-ISNULL( LAG ( [接听语音留言总数] ) OVER ( partition BY [用户] ORDER BY [排序] ), 0 ) as [语音留言],
[接听语音留言]
from (SELECT
[日期],
[用户],
[语音留言],
[接听语音留言],
SUM ( [语音留言] ) OVER ( PARTITION BY [用户] ORDER BY CAST(case when len([日期])=9 then SUBSTRING([日期],6,4) else SUBSTRING([日期],7,4) end AS int)+ CAST(case when len([日期])=9 then SUBSTRING([日期],4,1) else SUBSTRING([日期],4,2) end AS int)+ CAST(SUBSTRING([日期],1,2) AS int) ) as [语音留言总数],
SUM ( [接听语音留言] ) OVER ( PARTITION BY [用户] ORDER BY CAST(case when len([日期])=9 then SUBSTRING([日期],6,4) else SUBSTRING([日期],7,4) end AS int)+ CAST(case when len([日期])=9 then SUBSTRING([日期],4,1) else SUBSTRING([日期],4,2) end AS int)+ CAST(SUBSTRING([日期],1,2) AS int) ) as [接听语音留言总数],
CAST(case when len([日期])=9 then SUBSTRING([日期],6,4) else SUBSTRING([日期],7,4) end AS int)+ CAST(case when len([日期])=9 then SUBSTRING([日期],4,1) else SUBSTRING([日期],4,2) end AS int)+ CAST(SUBSTRING([日期],1,2) AS int) as [排序]
FROM
[t_test]
) as b order by CAST(case when len([日期])=9 then SUBSTRING([日期],6,4) else SUBSTRING([日期],7,4) end AS int)+ CAST(case when len([日期])=9 then SUBSTRING([日期],4,1) else SUBSTRING([日期],4,2) end AS int)+ CAST(SUBSTRING([日期],1,2) AS int);
测试数据: