首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL -使用频率(模式)计算激励

SQL -使用频率(模式)计算激励
EN

Stack Overflow用户
提问于 2018-09-28 06:46:39
回答 2查看 290关注 0票数 0

我希望使用一个SQL查询来计算incentive列,并根据一个月内学生接受辅导的次数。

如果学生在一个月内在AP Math接受了两次辅导,那么导师将得到20美元,否则将获得0美元。

我不想把日期分组到一个月的总结中,所以,我想留下日期,因为这就是为什么我为每个记录分配了10美元,在每个记录中,每个月被辅导两次的学生。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-28 11:07:08

我想你只是需要窗口功能:

代码语言:javascript
复制
select t.*,
       (case when cnt = 2 then 10 else 0 end) as incentive
from (select t.*,
             count(*) over (partition by studentid, subject, tutor, year(studentvisitdate), month(studentvisitdate) as cnt
      from t
     ) t
票数 0
EN

Stack Overflow用户

发布于 2018-09-28 08:33:49

初始化数据

代码语言:javascript
复制
declare @StudentTable as table
(
    StudentVisitDate  date,
    StudentId int,
    StudentName varchar(100),
    [Subject] varchar (30),
    Tutor varchar(100),
    Incentive int
)

insert into @StudentTable
values
('2018-August-03',123,'Terry Brooks','AP Math','Shawn Green',10)
,('2018-August-04',123,'Terry Brooks','AP Science','Ted Berry',10)
,('2018-August-07',123,'Terry Brooks','Music','Shawn Green',10)
,('2018-September-03',123,'Terry Brooks','AP Math','Shawn Green',10)
,('2018-September-04',123,'Terry Brooks','AP Science','Ted Berry',10)
,('2018-September-07',123,'Terry Brooks','AP Math','Shawn Green',10)

每月获得访问次数,将数据分组

代码语言:javascript
复制
;with temp as
(
select
StudentId,  Subject,    Tutor,Month(StudentVisitDate) [month]
,max(StudentVisitDate) maxdate -- the date on which the incentive will be calculated
,Count(StudentVisitDate) [count]
from @StudentTable
Group by
StudentId,  Subject,    Tutor,Month(StudentVisitDate)
)

利用上表中的信息获取每个月的有效激励

代码语言:javascript
复制
select
s.StudentVisitDate  ,
s.StudentId ,
s.StudentName ,
s.[Subject] ,
s.Tutor ,
Case
when t.maxdate = s.StudentVisitDate -- the incentive will be applied on the maximum date
then
 s.Incentive*t.count
 else
 0
 end Incentive
from @StudentTable s
inner join temp t
on s.StudentId=t.StudentId
and s.Subject =t.Subject
and s.Tutor=t.Tutor
and Month(s.StudentVisitDate)=t.month
order by StudentVisitDate

最终产出-

代码语言:javascript
复制
StudentVisitDate    StudentId   StudentName Subject Tutor   Incentive
2018-08-03  123 Terry Brooks    AP Math Shawn Green 10
2018-08-04  123 Terry Brooks    AP Science  Ted Berry   10
2018-08-07  123 Terry Brooks    Music   Shawn Green 10
2018-09-03  123 Terry Brooks    AP Math Shawn Green 0
2018-09-04  123 Terry Brooks    AP Science  Ted Berry   10
2018-09-07  123 Terry Brooks    AP Math Shawn Green 20
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52549812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档