我有一张桌子,我可以在其中找到完成课程(每门课程)平均需要多长时间
StudentName |课程| TimetoCompleteCourse
约翰尼|法语| 2
肖恩|英语| 3
芭芭拉|法语| 8个
现在我要对此进行分类:
课程|平均TimeToComplete |分类
法语| 4 | 2-4个月
英语| 3 | 1-3个月
如您所见,我想在三个月内对它们进行分类。 我知道使用Case语句,但我觉得这可以通过使用mod 3或其他东西更聪明地处理...
任何想法/建议?
这就是我现在所拥有的
Category = CASE
WHEN avg(TimeToCompleteCourse) <=3 THEN '1-3 months'
WHEN avg(TimeToCompleteCourse) >=4 AND avg(TimeToCompleteCourse) <=6 THEN '4-6 months'
WHEN avg(TimeToCompleteCourse) >=7 AND avg(TimeToCompleteCourse) <=9 THEN '7-9 months'
WHEN avg(TimeToCompleteCourse) >=10 AND avg(TimeToCompleteCourse) <=12 THEN '10-12 months'
WHEN avg(TimeToCompleteCourse) >=13 AND avg(TimeToCompleteCourse) <=15 THEN '13-15 months'
WHEN avg(TimeToCompleteCourse) >=16 AND avg(TimeToCompleteCourse) <=18 THEN '16-18 months'
WHEN avg(TimeToCompleteCourse) >=19 AND avg(TimeToCompleteCourse) <=21 THEN '18-21 months'
WHEN avg(TimeToCompleteCourse) >=22 AND avg(TimeToCompleteCourse) <=24 THEN '22-24 months'
WHEN avg(TimeToCompleteCourse) >=25 AND avg(TimeToCompleteCourse) <=27 THEN '25-27 months'
WHEN avg(TimeToCompleteCourse) >=28 THEN 'Way too long!'
END
答案 0 :(得分:3)
在我看来,你不需要模数运算符。 mod运算符将从整数除法返回余数(11 mod 3 = 2)。相反,我认为你想要舍入到最近的3个月间隔。更具体地说,取平均持续时间并将其四舍五入到最接近的3。
试试这个:
Select Course,
Avg(TimeToCompleteCourse) As AvgTimeToComplete,
Convert(VarChar(4), Ceiling(Avg(TimeToCompleteCourse) / 3.0) * 3 - 2)
+ ' - ' +
Convert(VarChar(4), Ceiling(Avg(TimeToCompleteCourse) / 3.0) * 3)
+ ' Months' As Category
From YourTableName
Group By Course
请注意,我重复计算,其中一个上面有-2。这只是为了显示值的范围。
答案 1 :(得分:2)
这(虽然丑陋)应该为所有模数值做技巧:
select
course
,CASE WHEN AVG(timetocompletecourse) > 27 THEN 'Way too long'
WHEN AVG(timetocompletecourse) < 4 THEN '1-3 Months'
WHEN AVG(timetocompletecourse)%3 = 0 THEN CAST(AVG(timetocompletecourse)-2 AS VARCHAR(2)) + '-' + CAST(AVG(timetocompletecourse) AS VARCHAR(2)) + ' Months'
WHEN AVG(timetocompletecourse)%3 = 1 THEN CAST(AVG(timetocompletecourse) AS VARCHAR(2)) + '-' + CAST(AVG(timetocompletecourse)+2 AS VARCHAR(2)) + ' Months'
WHEN AVG(timetocompletecourse)%3 = 2 THEN CAST(AVG(timetocompletecourse)-1 AS VARCHAR(2)) + '-' + CAST(AVG(timetocompletecourse)+1 AS VARCHAR(2)) + ' Months'
END as rangename
FROM yourtable
GROUP BY
course