1

我有一张表格,我可以在其中找到完成一门课程平均需要多长时间(每门课程)

学生姓名 | 课程 | 完成课程的时间

强尼 | 法语 | 2
肖恩 | 英语 | 3
芭芭拉 | 法语 | 8

现在我想对它进行分类:

课程 | 平均完成时间 | 类别

法语 | 4 | 2-4 个月
英语 | 3 | 1-3个月

如您所见,我想将它们分类为三个月。我知道使用案例陈述,但我觉得这可以更聪明地处理,fe通过使用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
4

2 回答 2

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。这只是为了显示值的范围。

于 2012-07-04T16:55:04.720 回答
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
于 2012-07-04T15:44:56.243 回答