sql中的累计和和累计计数



我正在尝试为患者建立治疗方案,下面是我正在制作的示例表。

tbody> <<tr>
PatientID SessionDate nextdate diff courses Coursenum course_Count Total session
1000012/13/20121.1开始1110
1000012/14/201212/13/20121现有1210
1000012/14/201212/14/20120现有1310
1000012/17/201212/14/20123现有1410
1000012/18/201212/17/20121现有1510
1000012/19/201212/18/20121现有1610
1000012/21/201212/19/20122现有1710
1000012/21/201212/21/20120现有1810
1000012/22/201212/21/20121现有1910
1000012/24/201212/22/20122现有11010
100009/17/20151/25/2013965开始2120
100009/18/20159/17/20151现有2220
100009/21/20159/18/20153现有2320
100009/22/20159/21/20151现有2420
100009/23/20159/22/20151现有2520
100009/25/20159/23/20152现有2620
100009/28/20159/25/20153现有2720
100009/29/20159/28/20151现有2820
100009/30/20159/29/20151现有2920
1000010/2/20159/30/20152现有21020
1000010/5/201510/2/20153现有21120
1000010/6/201510/5/20151现有21220
1000010/7/201510/6/20151现有21320
1000010/9/201510/7/20152现有21420
1000010/12/201510/9/20153现有21520
1000010/13/201510/12/20151现有21620
1000010/14/201510/13/20151现有21720
1000010/16/201510/14/20152现有21820
1000010/19/201510/16/20153现有21920
1000010/20/201510/19/20151现有22020

我认为使用count()和sum()的窗口函数在这里可以按正确的顺序工作。

select count(coursenum) over (partition by coursenum order by sessiondate)应该得到你的累计计数。

只要我们想在原始数据本身中显示组级聚合,就可以在SQL中使用窗口函数。

select *, max(course_Count) over (partition by Coursenum order by Session_date) as Total_Session 
from( select *, count(*) over (partition by Coursenum order by Session_date) as course_Count 
from( select *,sum(case when courses = 'start' then 1 else 0 end) over (order by Session_date) as Coursenum
from [table_name]
) A)

有关窗口函数的更多信息,请参阅此链接这是Case语句

相关内容

  • 没有找到相关文章