我希望通过SQL查询来计算incentive
列,并基于一个月内给学生补习的次数。
如果该学生每月在AP Math
中接受过两次补习,则导师将获得20美元,否则为0美元。
我不想将日期分组为月份摘要,因此,我想按原样保留日期,因此我为每条记录每月分配两次辅导的学生分配10美元。
答案 0 :(得分:0)
初始化数据
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)
获取每月访问次数,将数据分组
;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)
)
使用上表中的信息获取每个月的有效奖励措施
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
最终输出-
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
答案 1 :(得分:0)
我认为您只需要窗口函数:
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